gpt4 book ai didi

mysql - SQL Inner Join 语句未给出所需结果

转载 作者:行者123 更新时间:2023-11-29 07:06:28 25 4
gpt4 key购买 nike

希望有人可以帮助我。我有以下两个表:

Table: locations
location_id user_id city state
1 1 Los Angeles CA
2 1 New York NY
3 1 Chicago IL
4 2 Dallas TX
5 3 Denver CO
6 4 Miami FL
7 5 Atlanta GA

Table: events
event_id user_id event_name event_date
1 1 My Event 1 2017-02-01
2 2 My Event 2 2017-03-01
3 3 My Event 3 2017-04-01
4 4 My Event 4 2017-05-01
5 5 My Event 5 2017-06-01

我正在运行以下查询:

SELECT e.event_id,  e.user_id, e.event_name, e.event_date,
l.user_id, l.city, l.state
FROM events e
INNER JOIN locations l
ON e.user_id = l.user_id
ORDER BY e.event_date ASC

我试图只获取事件表中的记录,但也拉取与两个表共有的 user_id 相匹配的相应城市和州。输出应该是:

 event_id   user_id     event_name    event_date    city          state
1 1 My Event 1 2017-02-01 Los Angeles CA
2 2 My Event 2 2017-03-01 Dallas TX
3 3 My Event 3 2017-04-01 Denver CO
4 4 My Event 4 2017-05-01 Miami FL
5 5 My Event 5 2017-06-01 Atlanta GA

谁能指出我在 SQL 语句中的错误吗?

最佳答案

您从未向我们提供用于决定为给定用户选择哪个位置的逻辑。一种方法是获取与给定用户关联的最小 location_id:

SELECT t1.*,
COALESCE(t2.city, 'NA'),
COALESCE(t2.state, 'NA')
FROM events t1
LEFT JOIN locations t2
ON t1.user_id = t2.user_id
INNER JOIN
(
SELECT user_id, MIN(location_id) AS min_location_id
FROM locations
GROUP BY user_id
) t3
ON t2.user_id = t3.user_id AND
t2.location_id = t3.min_location_id

关于mysql - SQL Inner Join 语句未给出所需结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41445895/

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