php - MySQL 中的条件 JOIN 语句

标签 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。我该怎么做?

最佳答案

改用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/

相关文章:

每个循环的php都不起作用

php - 表单上传图像,存储在数据库中并显示(需要时)

mysql - 在 SQL 中将列名定义为另一个名称?

sql - 查询列出 IBM DB2 中所有可用的数据库

sql - 如何将postgres 12生成的sql文件恢复到postgres 9.6数据库中

php - Symfony2 Twig 迭代器

php - 使用php mysql为div分配不同的类名

sql - 如何在 Visual Studio 中使用 SSDT 重命名表

php - Laravel 仅针对一个路由/ Controller 给出 CORS 错误

javascript - 使用 $.getJSON 时可以将变量发送到 PHP 代码吗?