我如何将这个MySQL查询最小化为一个?

时间:2011-04-04 12:49:30

标签: mysql

我有这三个查询我想最小化这一个。我该怎么做?

    $query  = "SELECT COUNT(*) FROM states WHERE id = 1";
    $query2 = "SELECT COUNT(*) FROM cities WHERE id = 5";
    $query3 = "SELECT COUNT(*) FROM areas WHERE id = 3";
如果有人给我指的是一些可以帮助我练习和理解MySQL命令的精彩网站或文章,我也将不胜感激。非常感谢。

编辑:我希望脚本返回一个结果(变量)中合并的行数。

2 个答案:

答案 0 :(得分:3)

嗯,在一个查询中执行此操作的唯一方法是:

SELECT 
(SELECT COUNT(*) FROM states WHERE id = 1) AS state_count,
(SELECT COUNT(*) FROM cities WHERE id = 5) AS city_count,
(SELECT COUNT(*) FROM areas WHERE id = 3) AS area_count

这几乎不能称为“优化”,因为还有3个表扫描,但无法避免,因为你想在三个不同的表上COUNT

修改

如果你想要一个三个数字的总和,那就是答案:

SELECT 
(
    (SELECT COUNT(*) FROM states WHERE id = 1) 
    + (SELECT COUNT(*) FROM cities WHERE id = 5) 
    + (SELECT COUNT(*) FROM areas WHERE id = 3)
) AS sum

答案 1 :(得分:3)

SELECT 'states', COUNT(*) FROM states WHERE id = 1
UNION
SELECT 'cities', COUNT(*) FROM cities WHERE id = 5
UNION
SELECT 'areas' , COUNT(*) FROM areas WHERE id = 3

编辑:我更喜欢@Silver Light的答案,但是由于他无法想到另一种方法,我想我会把这个作为参考。