gpt4 book ai didi

SQL - 混合内部连接和左连接

转载 作者:行者123 更新时间:2023-12-04 19:25:25 25 4
gpt4 key购买 nike

我有一个包含三个表的 SQL Server 数据库:Gang、GangMember 和 Neighborhood。这些表的结构如下:

Neighborhood
------------
ID (non-null)
Name (non-null)

Gang
----
ID (non-null)
Name (non-null)
NeighborhoodID (nullable)

GangMember
----------
ID (non-null)
GangID (non-null)
Name (non-null),
Position (nullable)

我需要获取一个帮派成员所属的所有帮派(是的,他们可以属于多个)。如果有邻居,我也需要归还它。我希望我的结果集采用以下形式:gang.name, neighborhood.name, member.position

到目前为止,我已经到了这里:

SELECT
g.[Name],
'' as 'Neighborhood' /* This what I don't know how to do */
m.[Position]
FROM
[Gang] g,
[GangMember] m
WHERE
m.[GangID]=g.[ID]

因为帮派可能没有邻居,所以我不确定如何完成此查询。有人可以帮帮我吗?谢谢!

最佳答案

试试这个:

SELECT
g.[Name],
n.[Name] as 'Neighborhood',
m.[Position]
FROM
[Gang] g INNER JOIN [GangMember] m ON m.[GangID]=g.[ID]
LEFT OUTER JOIN [Neighborhood] n ON g.[NeighborhoodID] = n.[ID]

关于SQL - 混合内部连接和左连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7309036/

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