MySQL UNION - 将两个单值查询输出到不同的列中

时间:2014-05-06 08:37:34

标签: php mysql sql

我有两个不同的表,我想从中提取唯一ID的数量。每个表的查询如下所示

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 +
+------+------+

这样,直接引用结果会更容易,而不是为了记住提交查询的顺序。

5 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分: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

答案 2 :(得分: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'
)

答案 3 :(得分: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

答案 4 :(得分:0)

如果我猜,你想要识别输出,并知道哪个值来自哪个表......

这是一个很好的伎俩

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),然后您就可以知道哪个值来自哪个来源。