gpt4 book ai didi

php - MySQL 中的条件 JOIN 语句

转载 作者:可可西里 更新时间:2023-11-01 06:55:27 25 4
gpt4 key购买 nike

我有以下有效的 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。我该怎么做?

最佳答案

改用LEFT JOIN。并且 COALESCE 因为一些记录为空(我猜)。试试看,

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)

关于php - MySQL 中的条件 JOIN 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12074645/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com