2014-05-06 25 views
0

我有两个不同的表,我想从中提取唯一ID的数目。每个单表查询如下所示MySQL UNION - 将两个单值查询输出到不同的列中

SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID` FROM `table1` 

SELECT COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` WHERE `condition`='true' 

我想这两个查询合并成一个单一的语句。我知道我可以使用数名从第一查询作为列名使用

SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID` FROM `table1` 
UNION ALL 
SELECT COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` WHERE `condition`='true' 

然而,这个输出是两个数值分成两行显示:

+------+ 
+ t1ID + 
+------+ 
+ 4 + 
+------+ 
+ 5 + 
+------+ 

有没有办法让UNION查询以相应的计数名称输出两列中的数据?即

+------+------+ 
+ t1ID + t2ID + 
+------+------+ 
+ 4 + 5 + 
+------+------+ 

这样,这将是一个更容易直接引用的结果,而不是起伏记得在查询提交的顺序。

回答

1
SELECT (SELECT COUNT(DISTINCT(`uniqueid`)) FROM `table1`) as `t1ID`, 
(SELECT COUNT(DISTINCT(`uniqueid`)) FROM `table2` WHERE `condition`='true') as `t2ID` 
+0

D'oh!太简单! * facepalm * – Tomm

+0

谢谢堆,队友。 – Tomm

+0

没问题... :) – PeterRing

0
select sub1.t1ID, sub2.t2ID 
from (SELECT uniqueid, COUNT(DISTINCT(`uniqueid`)) as `t1ID` FROM `table1`) sub1 
join (SELECT uniqueid, COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` 
     WHERE `condition`='true') sub2 on sub1.uniqueid=sub2.uniqueid 
0

试试这个

select sum(t1ID) as t1ID 
    , sum(t2ID) as t2ID 
from (
    SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID`, 0 as `t2ID` FROM `table1` 
    union all 
    SELECT 0 as `t1ID`, COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` 
    WHERE `condition`='true' 
) 
0
select sum(t1ID) as t1ID , sum(t2ID) as t2ID 
(
    SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID`, 0 as `t2ID` FROM `table1` 
    UNION ALL 
    SELECT 0 as `t1ID` , COUNT(DISTINCT(`uniqueid`)) as `t2ID` FROM `table2` WHERE `condition`='true' 
)t 

确保将派生表的别名,因为我有t否则你会得到错误的

Every derived table must have its own alias 
0

如果我猜的,你想识别输出,并知道哪个VA泰伦从哪个表...

一个好的技巧是这个

SELECT COUNT(DISTINCT(`uniqueid`)) as `t1ID`, 't1ID' as 'X' FROM `table1` 
UNION ALL 
SELECT COUNT(DISTINCT(`uniqueid`)) as `t2ID`, 't2ID' as 'X' FROM `table2` WHERE `condition`='true' 

增加,“t1ID”和“T2ID”将出现接近计 值和读取行时,得到第二值(按名称X),那么你可以知道哪个值来自哪个来源。

相关问题