如何在一个查询中的不同行上左连接同一表

发布于 2024-12-10 12:51:32 字数 258 浏览 0 评论 0原文

我需要修复以下查询:

SELECT *
FROM message_treads
LEFT JOIN usernames ON usernames.uid=message_treads.uid_1
LEFT JOIN usernames ON usernames.uid=message_treads.uid_2

我知道我应该使用别名,但我不确定如何在这里执行此操作。我知道当一张表只有一个左连接时该怎么做,但是当有多个表时该怎么做呢?

I need to fix following query:

SELECT *
FROM message_treads
LEFT JOIN usernames ON usernames.uid=message_treads.uid_1
LEFT JOIN usernames ON usernames.uid=message_treads.uid_2

I know i should use aliases, but i am not sure on how to do it here. I know how to do it when there is only one left join of one table, but how to to it when there are more than one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拒绝两难 2024-12-17 12:51:32

您可以这样做:

SELECT *
FROM message_treads
LEFT JOIN usersnames ON usernames.uid IN (message_treads.uid_1, message_tread.uid_2)

至于别名,您可以这样做:

SELECT *
FROM message_treads
LEFT JOIN usernames AS user1 ON user1.uid = message_treads.uid_1
LEFT JOIN usernames AS user2 ON user2.uid = message_treads.uid_2

但这可能不是您想要的,因为这将从双倍用户名表中返回两组列。上面的第一个版本将仅返回一组用户名列。

You can do this:

SELECT *
FROM message_treads
LEFT JOIN usersnames ON usernames.uid IN (message_treads.uid_1, message_tread.uid_2)

As for aliasing, you'd do it like this:

SELECT *
FROM message_treads
LEFT JOIN usernames AS user1 ON user1.uid = message_treads.uid_1
LEFT JOIN usernames AS user2 ON user2.uid = message_treads.uid_2

But that's probably not what you want, as this'll return two sets of columns from the doubled-up usernames tables. The first version above will return only one set of username columns.

橘味果▽酱 2024-12-17 12:51:32

你是对的,你需要使用别名,如下所示:

SELECT *
FROM message_treads
LEFT JOIN usernames uid1 ON uid1.uid=message_treads.uid_1
LEFT JOIN usernames uid2 ON uid2.uid=message_treads.uid_2 

You are correct, you need to use aliases like so:

SELECT *
FROM message_treads
LEFT JOIN usernames uid1 ON uid1.uid=message_treads.uid_1
LEFT JOIN usernames uid2 ON uid2.uid=message_treads.uid_2 
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文