如何在单个查询中编写具有多个where条件的多个select语句?

时间:2016-08-25 06:48:30

标签: php sql

我正在使用sql编写php。我在数据库中有一个teachers_rating表我希望获得评分,例如有多少成员给5评级,就像只有4,像3一样...我用这个sql查询检查一次。

    SELECT COUNT( teachers_rating.rating ) AS fivestar
    FROM teachers_rating
    WHERE rating = '5' and id='23'
    UNION
    SELECT COUNT( teachers_rating.rating ) AS fourstar
    FROM teachers_rating
    WHERE rating = '4'and id='23'
    UNION
    SELECT COUNT( teachers_rating.rating ) AS threestar
    FROM teachers_rating
    WHERE rating = '3'and id='23'

like that its running but out output is
fivestar    
18
14
20

but iwant this type of structure
fivestar    fourstar threestar
18           14          20

如果有人知道请帮助我。

3 个答案:

答案 0 :(得分:0)

试试这个。

Select SUM(if(rating = '5',1,0) as fivestar,SUM(if(rating = '4',1,0) as fourstar,SUM(if(rating = '3',1,0) as threestar FROM teachers_rating where id='23'

答案 1 :(得分:0)

这称为条件聚合:

SELECT COUNT(CASE WHEN t.rating =5 THEN 1 END) as five,
       COUNT(CASE WHEN t.rating =4 THEN 1 END) as four,
       COUNT(CASE WHEN t.rating =3 THEN 1 END) as three
FROM teachers_rating t
WHERE t.id = '23'

如果您希望所有IDs动态显示:

SELECT t.id,
       COUNT(CASE WHEN t.rating =5 THEN 1 END) as five,
       COUNT(CASE WHEN t.rating =4 THEN 1 END) as four,
       COUNT(CASE WHEN t.rating =3 THEN 1 END) as three
FROM teachers_rating t
GROUP BY t.id

答案 2 :(得分:0)

以最简单的形式,您应该可以使用:

SELECT(SELECT ...)AS fivestar,(SELECT ...)AS fourstar,(SELECT ...)AS threestar