合并多个类似的查询

时间:2018-02-01 10:25:34

标签: mysql mysqli mysql-workbench

我可以从多个但简单的查询中获得结果,但我想将它们进一步合并为子查询。

所有子查询都与此相似 -

SELECT COUNT(count) AS acc1 FROM (SELECT COUNT(table.colname) AS count 
FROM tablename GROUP BY tablename.sumcol HAVING count=1) as access1

其他人也将

SELECT COUNT(count) AS acc2 FROM (SELECT COUNT(table.colname) AS count
 FROM tablename GROUP BY tablename.sumcol HAVING count=2) as access2

1 个答案:

答案 0 :(得分:1)

您可以使用UNION ALL在同一结果集中获取结果

  SELECT 'acc1' , COUNT(count) 
  FROM ( SELECT COUNT(table.colname) AS count 
      FROM tablename G
      ROUP BY tablename.sumcol 
      HAVING count=1)  access1

  UNION ALL

  SELECT 'acc2', COUNT(count) 
  FROM (SELECT COUNT(table.colname) AS count
      FROM tablename 
      GROUP BY tablename.sumcol 
      HAVING count=2)  access2

我添加了' acc1'和' acc2'字面值可以获得更好的结果,但是你可以避免它

事实上你的查询只有一行,如果你需要在同一行上有两个结果,你可以使用交叉连接(笛卡尔积)

  SELECT COUNT(count) as count_acc1, T.count2
  FROM ( SELECT COUNT(table.colname) AS count1
      FROM tablename G
      GROUP BY tablename.sumcol 
      HAVING count=1)  access1

  CROSS JOIN (

  SELECT COUNT(count)  as count2
  FROM (SELECT COUNT(table.colname) AS count
      FROM tablename 
      GROUP BY tablename.sumcol 
      HAVING count=2)  access2 ) T