mysql数据库两表关联查询统计同一字段不同值的个数

数据表如下:

统计总数

SELECT h.*,IFNULL(count(r.pid),0) AS 总数
FROM rts_room AS r RIGHT JOIN rts_house AS h
ON r.pid = h.Id
AND r.state != 3
WHERE h.state = 0
GROUP BY h.Id

输出结果如下:

统计总数及闲置的个数

SELECT 
h.*,
SUM(CASE r.state WHEN "0" THEN 1 ELSE 0 END)+
SUM(CASE r.state WHEN "1" THEN 1 ELSE 0 END) AS 总数,
SUM(CASE r.state WHEN "0" THEN 1 ELSE 0 END) AS 闲置
FROM rts_room AS r RIGHT JOIN rts_house AS h
ON r.pid = h.Id
WHERE h.state = 0
GROUP BY h.Id

输出结果如下:

 

posted @ 2019-08-19 11:25  懒得起名字ya  阅读(9811)  评论(0编辑  收藏  举报