goods表数据:
goods_use表数据:
goods_status表数据:
表间关系:
表goods属性gds_id作为表goods_use的外键,表goods的属性status取值与goods_status的id对应
要求统计出某一unit_name下各个goods的status,使用left join保留goods_ststus的所有id,使用IFNULL为连接得到的空值赋初始值0.
sql语句(如unit_name="1"):
SELECT gt.id statu ,IFNULL(gg.num,0) num
from goods_status gt
LEFT JOIN (
SELECT gd.unit_name ,gt.id tid,gu.status,COUNT(gu.`status`) num
from goods gd
LEFT JOIN goods_use gu on gd.gds_id = gu.gds_id
RIGHT JOIN goods_status gt on gt.id=gu.`status`
WHERE gd.unit_name="1"
GROUP BY gu.`status`
) gg on gt.id=gg.status
ORDER BY gt.id
当goods_use表status值包含了所有goods_status的id时,通过goods_use表子查询也能实现相同功能:
SELECT gt.`status` statu ,IFNULL(gg.num,0) num
from (
select DISTINCT goods_use.`status` `status`
from goods_use
) gt
LEFT JOIN (
SELECT gu.`status` status , COUNT(gu.`status`) num
from goods gd
LEFT JOIN goods_use gu on gd.gds_id = gu.gds_id
WHERE gd.unit_name=#{unitName}
GROUP BY gu.`status`
) gg on gt.`status`= gg.status
ORDER BY gt.`status`
查询结果: