gpt4 book ai didi

Mysql,双重连接两次使用同一张表,但间接

转载 作者:行者123 更新时间:2023-11-29 05:33:08 26 4
gpt4 key购买 nike

有很多关于同表join的问题,但是我找不到与我的问题相关的东西

我有两个表:

user (id, name)
friends (from, to)

我有以下查询。它应该检索所有用户和他们的 friend :

SELECT user.id, user.name, f.to, friend.id, friend.name
FROM user

LEFT JOIN friends f ON user.id = f.from
LEFT JOIN user friend ON user.id = f.to
LIMIT 0, 200

它返回这样的东西:

id name from to id   name
1 bob 1 3 NULL NULL
1 bob 1 4 NULL NULL
2 toto 2 7 NULL NULL

from 和 two 是正确的,但是第二个 join 好像不行。您知道第二次加入有什么问题吗?

最佳答案

试试这个:

SELECT user.id, user.name, f.to, friend.id, friend.name
FROM user
LEFT JOIN friends f ON user.id = f.from
LEFT JOIN user friend ON friend.id = f.to
LIMIT 0, 200

请注意,我在连接条件中将 user 替换为 friend

关于Mysql,双重连接两次使用同一张表,但间接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13009813/

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