对同一个表使用左连接还是有更好的方法?
我有一个名为 bans
的表,其中包含以下字段:
room_id, banned_user_id, banned_by_id, reason, ts_start, ts_end
用户数据来自名为 users
的表,现在我想查询禁令以检索谁的姓名被禁止、被禁止者以及原因、禁止的时间和结束的时间。
所以我有这个查询:
SELECT u.username, us.username, b.reason, b.ts_start, b.ts_end
FROM `bans` b
LEFT JOIN users us ON b.banned_by_uid = us.uid
LEFT JOIN users u ON b.banned_uid = u.uid
WHERE room_id = 3
我的问题是我的查询是否可以通过使用 LEFT JOIN 来获取我必须从表 users
中获取的 2 个数据,或者有不同的方法有点场景?
I have a table called bans
where I have the follow fields:
room_id, banned_user_id, banned_by_id, reason, ts_start, ts_end
The users data come from the table called users
, now I wanted to query the bans to retrive the name of who was banned and by who along with reason, time the ban was placed and time it ends.
So I have this query:
SELECT u.username, us.username, b.reason, b.ts_start, b.ts_end
FROM `bans` b
LEFT JOIN users us ON b.banned_by_uid = us.uid
LEFT JOIN users u ON b.banned_uid = u.uid
WHERE room_id = 3
My question here is wether my query is ok by using the LEFT JOIN for the 2 data I have to grab from the table users
or there is a different approach for this kinda of scenario ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的询问完全可以接受。每个
users
的加入都在一个特定的 ID 上,这转化为一个简单的查找,并且开销最小。Your query is perfectly acceptable. Each join to
users
is on a specific ID, which translates into a simple lookup, with minimal overhead.