gpt4 book ai didi

mysql - 如何在 SQL 中有条件地定义 JOIN 的 ON 值?

转载 作者:行者123 更新时间:2023-11-29 14:43:12 24 4
gpt4 key购买 nike

我遇到了条件加入的问题。

这是我的查询:

SELECT table_b.name
FROM table_a
LEFT JOIN table_b
ON table_a.id = table_b.a_id

我的 table_b 的描述:

id, a_id, ref_z, name
----------------------
1 | 0 | 1 | James
2 | 0 | 2 | John
3 | 2 | 2 | John. S
4 | 0 | 3 | Martin
5 | 6 | 3 | Martin. M
6 | 2 | 3 | Martin. M. Mr

假设我有一个参数@a_id。

如果 table_a.id = @a_id 存在于 0 上,我想将 table_a 和 table_b 连接起来。

因此上一个查询的输出将是(@a_id = 2):

James
John. S
Martin. M. Mr

有人有一个想法、博客文章、手册页或其他任何可以引导我找到正确查询的东西吗?

谢谢,

最佳答案

where a_id = 2 

您的连接可以缩短为using (a_id),因为两列具有相同的名称并且没有歧义。

on/using 不应与谓词子句 (where) 混淆

关于mysql - 如何在 SQL 中有条件地定义 JOIN 的 ON 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7566097/

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