MySQL中的条件JOIN语句

时间:2012-08-22 13:50:06

标签: php mysql sql join

我有以下工作MySQL查询:

SELECT 
    a.id id,
    a.price price,
    a.stock stock,
    a.max_per_user max_per_user,
    a.purchased purchased, 
    b.quantity owned 
FROM 
    shop_items a 
        JOIN shop_inventory b 
            ON b.iid=a.id 
            AND b.cid=a.cid 
WHERE 
    a.cid=1 
    AND a.szbid=0 
    AND a.id IN(3,4)

JOIN加入表shop_inventory b以返回b.quantity owned。但是,如果shop_inventory b表中没有记录b.iid=a.id,我希望它返回b.quantity = 0。我该怎么做?

4 个答案:

答案 0 :(得分:9)

请改用LEFT JOIN。并且COALESCE因为某些记录为null(我猜)。尝试,

SELECT a.id id,a.price price,a.stock stock,
       a.max_per_user max_per_user,a.purchased purchased, 
       COALESCE(b.quantity, 0) owned 
FROM shop_items a 
          LEFT JOIN shop_inventory b 
                ON b.iid=a.id AND b.cid=a.cid 
WHERE a.cid=1 AND 
      a.szbid=0 AND 
      a.id IN(3,4)

答案 1 :(得分:3)

这样的事情应该可以解决问题。

SELECT a.id id,a.price price,a.stock stock,
       a.max_per_user max_per_user,a.purchased purchased, 
       COUNT(b.quantity) AS owned 
FROM shop_items a 
          LEFT JOIN shop_inventory b 
                ON b.iid=a.id AND b.cid=a.cid 
WHERE a.cid=1 AND a.szbid=0 AND a.id IN(3,4)
GROUP BY id

答案 2 :(得分:3)

您想使用LEFT JOIN代替JOIN

SELECT a.id id,a.price price,a.stock stock,
       a.max_per_user max_per_user,a.purchased purchased, 
       b.quantity owned 
FROM shop_items a 
LEFT JOIN shop_inventory b ON b.iid=a.id AND b.cid=a.cid 
WHERE a.cid=1 AND a.szbid=0 AND a.id IN(3,4)

如果b中的字段与ON子句不匹配,则会使这些字段为空。

如果您希望它为0,则可以使用IFNULL

SELECT IFNULL(b.quantity, 0) owned

答案 3 :(得分:2)

这是您使用Left Join和Group By的地方。如果您只需要b中的项目数,那就是。

SELECT a.id id,a.price price,a.stock stock,
       a.max_per_user max_per_user,a.purchased purchased, 
       COUNT(b.quantity owned) as quantity_owned
FROM shop_items a 
          LEFT JOIN shop_inventory b 
                ON b.iid=a.id AND b.cid=a.cid 
WHERE a.cid=1 AND a.szbid=0 AND a.id IN(3,4)
GROUP BY a.id