【问题标题】:Mysql, double join that use the same table twice, but indirectlyMysql,两次使用同一张表的双重连接,但间接
【发布时间】:2012-10-22 10:47:40
【问题描述】:

有很多关于在同一张桌子上加入的问题,但我找不到与我的问题相关的东西

我有两张桌子:

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

我有以下查询。它应该检索所有用户及其朋友:

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 似乎不起作用。你知道第二次加入有什么问题吗?

【问题讨论】:

    标签: mysql join self-join


    【解决方案1】:

    试试这个:

    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

    【讨论】:

    • 不敢相信我错过了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2017-07-27
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多