【问题标题】:How to Join two related tables, while a record in one, refers to two records in the other?如何连接两个相关的表,一个记录中的一个引用另一个中的两个记录?
【发布时间】:2013-04-03 16:02:36
【问题描述】:

我有一个包含 sender_id 和 receiver_id 字段的事务表,以及另一个包含 user_id first_name last_name 等的用户表...

我想从交易中查询数据并从用户那里加入详细信息 问题是我需要为发送者和接收者带来名字和姓氏......

SELECT t.* u.*
FROM transactions t, users u
WHERE t.sender_id = u.user_id OR t.receiver_id = u.user_id

这当然不是解决方案,因为我无法知道结果集中哪个是发送者/接收者,但它有助于说明问题

有什么想法吗? 谢谢 半开

【问题讨论】:

    标签: mysql sql relational-database


    【解决方案1】:

    您需要在表transactions 上连接表users 两次,因为事务中有两列依赖于表users

    SELECT  a.*,
            b.firstName as SenderName,
            c.FirstName as RecieverName
    FROM    transactions a
            INNER JOIN users b
                ON a.sender_ID = b.user_ID
            INNER JOIN users c
                ON a.reciever_id = c.user_ID
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-10-08
      • 1970-01-01
      • 2017-06-11
      • 1970-01-01
      • 2021-12-10
      • 2022-11-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多