选择具有不同条件的列两次

时间:2017-09-22 19:21:59

标签: mysql sql

我有两个表,表1和表2,表1有member_id,名字和姓氏, 表2有buyer_id和seller_id我想在一行中选择买家和卖家的名字和姓氏

    Table_1
   member id | firstname | lastname
    1        |  John     |  Richard
    2        | Joseph    |   Curly
    3        |  Ismail   |  Jake
    4        | Elijah    |   Michael

    Table_2
  seller_id  | buyer_id|
    2        |     1   |
    3        |     4   |

我一直在尝试返回一个包含这样的行的表

 seller_id | buyer_id | firstname | lastname | firstname | lastname|
     2     |   1      |    Joseph |   Curly  |  John     | Richard |

我使用的查询是

SELECT a.firstname,a.lastname,a.firstname,a.lastname,b.seller_id,b.buyer_id
        FROM Table_1 as a,Table_2 as b WHERE b.buyer_id = a.member_id

1 个答案:

答案 0 :(得分:1)

您需要加入table_1两次(一个用于加入seller_id,另一个用于加入buyer_id

SELECT 
    a.firstname
    ,a.lastname
    ,c.firstname
    ,c.lastname
    ,b.seller_id
    ,b.buyer_id
    FROM Table_2 as b
    INNER JOIN Table_1 as a ON a.member_id = b.seller_id
    INNER JOIN Table_1 as c On c.member_id = b.buyer_id