即使其中没​​有车,我也需要显示BRAND_CAR的所有车

时间:2019-06-18 07:12:22

标签: mysql sql ifnull

我创建了此查询,即使在车辆表上创建了0辆车辆,也无法显示所有品牌的汽车。

SELECT BRAND_CAR_NAME, COUNT(*)
FROM brand b, vehicule v, model mo
WHERE v.ID_MODEL = mo.ID_MODEL
AND mo.ID_BRAND = b.ID_BRAND
GROUP BY BRAND_CAR_NAME

它显示了什么:

Brand 1 :   1
Brand 3 :   1 
Brand 4 :   1
Brand 6 :   1

我想看看:

            Brand 1 : 1
            Brand 3 : 1 
            Brand 4 : 1
            Brand 6 : 1
            brand 2 : 0
            brand 5 : 0
            brand 7 : 0
SELECT NOM_MARQUE, IFNULL(v.ID_VOITURE)
FROM marque m, voiture v, model mo
WHERE v.ID_MODEL = mo.ID_MODEL
AND mo.ID_MARQUE = m.ID_MARQUE
GROUP BY NOM_MARQUE

2 个答案:

答案 0 :(得分:1)

使用Left Join获取结果,请尝试以下查询

SELECT b.BRAND_CAR_NAME, COUNT(*) 
FROM brand b
LEFT JOIN model mo ON b.ID_BRAND = mo.ID_BRAND
INNER JOIN vehicule v ON mo.ID_MODEL = v.ID_MODEL
GROUP BY b.BRAND_CAR_NAME;

答案 1 :(得分:0)

您可以使用LEFT JOIN,尤其是在vehicule表与SUM( IFNULL(SIGN(v.ID_MODEL),0) )之前使用

我认为最好在LEFT JOIN表之前使用model,再次丢失model表的记录

SELECT BRAND_CAR_NAME, SUM( IFNULL(SIGN(v.ID_MODEL),0) ) as BRAND_COUNT
  FROM brand b
  LEFT JOIN model mo ON mo.ID_BRAND = b.ID_BRAND
  LEFT JOIN vehicule v ON v.ID_MODEL = mo.ID_MODEL
 GROUP BY BRAND_CAR_NAME;

Demo