这是我的陈述:
SELECT
a.size AS 'size_id',
b.size,
a.stock,
a.id AS 'stock_id',
IFNULL(c.quantity,0) as 'cart_qty'
FROM
stock a
JOIN
sizes b ON a.size = b.id
LEFT JOIN
cart_items c ON a.id = c.stock_id
WHERE
a.product_id = '{$product['id']}'
AND
c.cart_id = '$cart_id'
AND
a.stock > 0
ORDER BY
b.display_order
在上面,$ cart_id可能为空,或者'cart_items'表中可能没有匹配项。如何改写上述内容,以便如果cart_items中没有匹配项,我仍然可以从与product_id匹配的库存中获得结果?但是如果cart_items中有匹配项,那么我会得到额外的列(cart_qty)?
答案 0 :(得分:2)
将谓词移到ON
子句:
LEFT JOIN
cart_items c ON a.id = c.stock_id AND c.cart_id = '$cart_id'
这样,如果cart_items
中没有匹配项,您仍会获得与stock
匹配的product_id
的结果。否则,如果cart_items
中有匹配项,则会正确填充其他列cart_qty
。
答案 1 :(得分:0)
我不确定你能否同时做到这两点。但是,如果$cart_Id is null
添加
AND ($cart_Id is null or c.cart_id = '$cart_id')