我有不同的MySQL SELECT查询,都有不同的where语句。这些产生总数,唯一总数,某种类型的总数。
所以对于实例:
Loc | total | unique | missing
London | 10 | 5 | 2
New York |20 |10 |5
目前我正在分别运行每个Select查询,但我宁愿一次运行它们。有没有办法在MySQL中做到这一点?
类似的东西:
SELECT
Location
Count(total)
SELECT
count(unique)
FROM
.. my tables..
WHERE
.. where clause for unique part ..
GROUP BY
unique
FROM
.. my tables ..
WHERE
.. where clause for total part ..
GROUP BY
total
答案 0 :(得分:2)
也许你想要的是一个UNION
SELECT * from table where...
UNION
SELECT * from table where...
显然,每个查询返回的列必须相同。
答案 1 :(得分:0)
我希望子查询(或几个)是有序的。
select location, (select count(total)
from totalTable
where totalTable.location = locationTable.location) as total,
(select count(uniqe)
from uniqeTable
where uniqeTable.location = locationTable.location) as uniqe,
(select count(missing)
from missingTable
where missingTable.location = locationTable.location) as missing
from locationTable
where locationCriteria = searchCriteria
如果需要,您可以在多个子查询中引用同一个表 - 只需尝试将它们连接到id上,最好是在正确索引的内容上。显然必须根据需要调整where子句。
答案 2 :(得分:0)
谢谢大家。对于任何试图掌握这一点的人来说,我的最终解决方案是:
SELECT
Geo,
total,
SUM(unique) as unique
FROM
(SELECT
Geo,
COUNT(total) AS total,
0 unique,
FROM
-- my tables --
WHERE
-- where clause for totals --
GROUP BY
Geo)
UNION
(SELECT
Geo,
0 total,
COUNT(unique) AS unique,
FROM
-- my tables --
WHERE
-- where clause for unique --
GROUP BY
Geo)
) as tmptable
GROUP BY
Geo