具有 2 个表连接的 MySQL 查询
我有一个像这样的users:
id username
1 user1
2 user2
3 user3
和一个像这样的msgs:
t_id sent_by id msg
1 2 1 whatever
2 3 1 is
3 2 1 here
其中users.id是主键,msgs.id< /strong> 是外键。在 msgs 表中,id 是 sent_by 发送的消息的目的地。
我想选择并显示 sent_by 的用户名,只要登录用户(通过会话)是msgs.id。
为了澄清问题,这里是我想要做的伪代码:
- 用户已登录。将其
userid
存储到session
。 - 显示向我(登录用户)发送消息的不同用户名。在上面的示例中,如果我的用户 id 为 1,则显示为:
user2, user3
。
我正在考虑使用 join,但最终对 sent_by 和 ids 进行了 2 次查询。这似乎不是一个有效的查询。
我应该怎么办?
I have a users like this:
id username
1 user1
2 user2
3 user3
and a msgs like this:
t_id sent_by id msg
1 2 1 whatever
2 3 1 is
3 2 1 here
Where users.id is a primary key and msgs.id is a foreign key. In the msgs table, id is the destination of the message sent by sent_by.
I want to select and display the username of sent_by as long as the logged in user (via sessions) is the msgs.id.
To clarify things, here is the pseudocode of what I wanted to do:
- Users has logged in. Store its
userid
tosession
. - Display the distinct usernames of who sent me (the logged in user) the messages. In the example above, the display will be:
user2, user3
if I have a user id of 1.
I was thinking of using join but ended up doing 2 queries for the sent_by and ids. It seems not an efficient query.
What should I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是一个简单的
JOIN
,因为您只想返回sent_by
id 的用户名。This is a straightforward
JOIN
since you only wish to return usernames of thesent_by
ids.