【问题标题】:how can I get a mysql result set that contains both matched and unmatched records如何获得包含匹配和不匹配记录的 mysql 结果集
【发布时间】:2020-01-18 22:22:16
【问题描述】:

我有以下表格:

suppliers
id  name
1   s1
2   s2
3   s3
products
id  name
1   ...
2   ...
..  ...
9   lemon
..  ...

product_suppliers
id supplier_id product_id  
1  2           9

我需要一个如下所示的结果集:

supplierName     productSupplier
s1               null
s2               1 
s3               null

我尝试了像下面这样的左连接:

select * from suppliers 
left join product_suppliers on suppliers.id = product_suppliers.supplier_id
where product_suppliers.product_id = 9

但结果集只包含与供应商 s2 相关联的柠檬,我还需要其他供应商用于未来的关联。

谢谢!

【问题讨论】:

    标签: mysql sql join left-join


    【解决方案1】:

    只需将条件从where 子句移动到left joinon 部分。 where 子句中的条件是强制性的,因此如果记录在 product_suppliers 中没有匹配项,它将从结果集中驱逐它。

    select s.name supplier_name, ps.id product_supplier
    from suppliers s
    left join product_suppliers ps on s.id = ps.supplier_id and ps.product_id = 9
    

    我还修改了您的查询以实施一些最佳做法:

    • 枚举SELECT子句中的列
    • 使用表别名

    【讨论】:

      【解决方案2】:

      删除 where 条件,这样您只过滤 id 为 9 的产品

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-02-06
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-08-29
        相关资源
        最近更新 更多