MySQL中的条件JOIN语句

Kei*_*ons 5 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)
Run Code Online (Sandbox Code Playgroud)

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

Joh*_*Woo 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)
Run Code Online (Sandbox Code Playgroud)