MySQL JOIN conditional expression

I have the following working MySQL query:

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)

JOINjoins the table shop_inventory bfor a refund b.quantity owned. However, if shop_inventory bthere is no record in the table in which b.iid=a.idI want it to return b.quantity = 0. How should I do it?

+5
source share
4 answers

Use LEFT JOINinstead. And COALESCE, since some of the entries are where null (I think). Give it a try

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)
+9
source

Something like this should do the trick.

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
+3
source

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 NULL, ON.

, 0, IFNULL

SELECT IFNULL(b.quantity, 0) owned
+3

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
+2
source

All Articles