【问题标题】:How to select the sender(data) and the recipient(data) using one SQL-query?如何使用一个 SQL 查询选择发件人(数据)和收件人(数据)?
【发布时间】:2017-07-15 21:04:51
【问题描述】:

所以,我正在使用 PHP 和 MySQL。我有一个表“通知”和一个表“用户”。通知给出了发送者和接收者。我做了一些研究并尝试了一些事情,但我无法找到解决方案。以下 SQL 查询为我提供了通知中的数据集以及收件人数据,但我如何才能在一次查询中从用户表中选择发件人数据?

SELECT notifications.id,notifications.recipient_id,notifications.sender_id,notifications.unread,notifications.type,notifications.parameters,notifications.created_at,users.id AS user_id,users.username 
FROM notifications, users 
WHERE users.id = notifications.recipient_id;

【问题讨论】:

    标签: php mysql multiple-users


    【解决方案1】:
    SELECT 
        notifications.id,
        notifications.recipient_id,
        notifications.sender_id,
        notifications.unread,
        notifications.type,
        notifications.parameters,
        notifications.created_at,
        users1.id AS user_id_recipient,
        users1.username  AS username_recipient,
        users2.id AS user_id_sender,
        users2.username  AS username_sender
    FROM notifications
    INNER JOIN users AS users1 ON users1.id = notifications.recipient_id
    INNER JOIN users AS users2 ON users2.id = notifications.sender_id
    

    【讨论】:

    • #1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 10 行的“.username_recipient, users2.id AS user_id_sender, users2.username AS us”附近使用正确的语法
    • 我编辑了。用答案的内容再试一次。
    • 谢谢!这就是解决方案!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多