【问题标题】:MySQL selecting all records and for each select separate record - in one queryMySQL 选择所有记录并为每个选择单独的记录 - 在一个查询中
【发布时间】:2014-11-12 09:09:21
【问题描述】:

我相信我在这里尝试实现的是嵌套查询 - 但是我不确定如何继续。

我有 2 个表 usersnotifications 我正在做的是查询 notifications 表以获取详细信息,但我也是 用户表上的左外连接以获取我的用户信息。我拥有的是这样的:

          USERS TABLE     
| user id | username | user image |


    NOTIFICATIONS TABLE  
| receiver id | sender id |

仅获取 receivers 信息不是问题,因为我使用以下查询:

SELECT
    notifications.senderID, notifications.receiverID, users.username, users.image
FROM
    notifications
    LEFT OUTER JOIN users ON users.id = notifications.receiverID
WHERE notifications.receiverID = ' xxx '

我需要添加的内容是一种查找记录的方法,同时获取 THAT 记录的 users.username 和 users.image(将对应于users.id for notifications.senderID)以及主记录(notifications.recieverID

如果可能我想将其保留在一个查询中并在 PHP foreach 循环之外。

【问题讨论】:

    标签: php mysql join


    【解决方案1】:

    以不同的别名加入users 表两次

    SELECT notifications.senderID, notifications.receiverID, 
           receiver.username as receiver_name, receiver.image as receiver_image,
           sender.username as sender_name, sender.image as sender_image
    FROM notifications
    LEFT OUTER JOIN users as receiver ON receiver.id = notifications.receiverID
    LEFT OUTER JOIN users as sender ON sender.id = notifications.senderID
    WHERE notifications.receiverID = ' xxx '
    

    【讨论】:

    • 我收到以下错误:“字段列表”中的未知列“users.image”
    • 您没有替换 select 子句中出现的所有 users 表。它必须是发送者或接收者
    【解决方案2】:

    这是例如查询

    选择 User.id, User.username, User.password, User.email, User.role, User.created, @987654333 @.modified, Userdetail.user_id, Userdetail.first_name, last name, Userdetail.address, Userdetail.telephone FROM cakephp_test.users AS User 左加入cakephp_test.userdetails AS Userdetail 开 (Userdetail.user_id = User.id) 其中User.id = 51 限制 1

    你的情况

    SELECT notification.senderID, notifications.receiverID, users.username, users.image FROM database_name.users 作为用户左连接 database_name.notification 作为通知 ON (users.id = notifications.receiverID) WHERE User.id = 'xxx'限制 1 个

    【讨论】:

      猜你喜欢
      • 2012-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多