具有 2 个表连接的 MySQL 查询

发布于 2024-12-18 15:01:26 字数 840 浏览 0 评论 0原文

我有一个像这样的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 表中,idsent_by 发送的消息的目的地。

我想选择并显示 sent_by用户名,只要登录用户(通过会话)是msgs.id

为了澄清问题,这里是我想要做的伪代码:

  1. 用户已登录。将其 userid 存储到 session
  2. 显示向我(登录用户)发送消息的不同用户名。在上面的示例中,如果我的用户 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:

  1. Users has logged in. Store its userid to session.
  2. 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 技术交流群。

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

发布评论

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

评论(2

铜锣湾横着走 2024-12-25 15:01:26

这是一个简单的 JOIN,因为您只想返回 sent_by id 的用户名。

$sql = "SELECT DISTINCT
    users.username
    msgs.sent_by
  FROM users JOIN msgs ON users.id = msgs.sent_by 
  WHERE id = {$_SESSION['my_userid']}";

This is a straightforward JOIN since you only wish to return usernames of the sent_by ids.

$sql = "SELECT DISTINCT
    users.username
    msgs.sent_by
  FROM users JOIN msgs ON users.id = msgs.sent_by 
  WHERE id = {$_SESSION['my_userid']}";
最后的乘客 2024-12-25 15:01:26
SELECT DISTINCT u.username, m.sent_by
FROM msgs m
INNER JOIN users u ON u.id = m.sent_by
WHERE m.id = {$_SESSION['userid']}
ORDER BY m.t_id DESC
SELECT DISTINCT u.username, m.sent_by
FROM msgs m
INNER JOIN users u ON u.id = m.sent_by
WHERE m.id = {$_SESSION['userid']}
ORDER BY m.t_id DESC
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文