开发者

how do i minimize this MySQL query to one?

i have this three query i would like to minimize this to one. how would i do it?

    $query  = "SELECT COUNT(*) FROM states WHERE id = 1";
    $query2 = "SELECT COUNT(*开发者_运维问答) FROM cities WHERE id = 5";
    $query3 = "SELECT COUNT(*) FROM areas WHERE id = 3";

also i would appreciate if someone points me to some great website or article that could help me practice and understand MySQL commands. thanks a lot.

EDIT : i would like the script to return the number of rows combined in one result(variable).


Well, the only way (i know) to do this in one query is this:

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

This hardly can be called an "optimization", beacuse there are also 3 table scans, but can't avoid those, since you want to COUNT on three different tables.

EDIT

If you want a sum of three numbers, then this is the answer:

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


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

EDIT: I like @Silver Light's answer better, but since (s)he couldn't think of another way to do it, I thought I'd leave this one here as a reference.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜