gpt4 book ai didi

mysql - 如果 ON 条件在 mysql 中没有匹配数据,如何获取 NULL

转载 作者:行者123 更新时间:2023-11-29 05:19:18 25 4
gpt4 key购买 nike

我在 mysql 中有 2 个表。我想加入它们,但即使第二个表中没有匹配的数据,我也需要显示 NULL 但加入它们。

table1

id | name
-----------
1 | name1
2 | name2
3 | name3

和第二张 table

table2

id | service | amount
------------------------
1 | service1 | 10
2 | service2 | 20
3 | service1 | 20
4 | service3 | 10

我需要的输出是,

output

name | amount
--------------
name1 | 10
name2 | NULL
name3 | 20

我试过以下查询

SELECT t1.name,t2.amount 
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
WHERE t2.service=1

但它不会返回 name2,因为在第二个表中没有匹配的 id。我该怎么做?

最佳答案

您的 where 子句将您的 left join 转换为 inner join*。将条件放在连接的 ON 子句中

SELECT t1.name,t2.amount 
FROM table1 t1
LEFT JOIN table2 t2 ON t1.id = t2.id
AND t2.service = 1

* 您在 where 子句中过滤连接表中的数据。这会强制过滤数据。

关于mysql - 如果 ON 条件在 mysql 中没有匹配数据,如何获取 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28044729/

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