【问题标题】:MySQL UNION - output two single value queries into different columnsMySQL UNION - 将两个单值查询输出到不同的列
【发布时间】:2014-05-06 08:37:33
【问题描述】:

我有两个不同的表,我想从中提取唯一 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 +
+------+------+

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

【问题讨论】:

    标签: php mysql sql


    【解决方案1】:
    SELECT (SELECT COUNT(DISTINCT(`uniqueid`))  FROM `table1` ) as `t1ID`,
    (SELECT COUNT(DISTINCT(`uniqueid`))  FROM `table2` WHERE `condition`='true') as `t2ID`
    

    【讨论】:

    • 天啊!太简单! 掌心
    • SELCT? --- 你的意思是SELECT@PeterRing
    • 救命稻草回答!谢谢@PeterRing
    【解决方案2】:
    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
    

    【讨论】:

      【解决方案3】:

      试试这个

      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'
      )
      

      【讨论】:

        【解决方案4】:
        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
        

        【讨论】:

          【解决方案5】:

          如果我猜,您想识别输出,并知道哪个表中的哪个值...

          这是一个很好的技巧

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

          【讨论】:

            猜你喜欢
            • 2014-02-13
            • 1970-01-01
            • 2020-08-25
            • 2018-08-08
            • 1970-01-01
            • 2013-06-01
            • 1970-01-01
            • 2023-03-16
            • 1970-01-01
            相关资源
            最近更新 更多