mysql数据库两表关联查询统计同一字段不同值的个数
程序员文章站
2022-05-09 20:52:50
...
数据表如下:
统计总数
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
输出结果如下:
上一篇: Java8之函数接口