如何将一个表的结果连接成对

时间:2014-05-19 15:21:37

标签: sql join inner-join

我有一张桌子

    nr_id | Name | Surname | roomate_id
      1   | Tom  | Hopkins |    4
      2   | Mike | Rubens  | 
      3   | Dylan| Obama   |    5
      4   | Jason| Lin     |    1
      5   | Peter| Huang   |    5
    ....  | .... | ....    | ....

是否可以将此表与sql查询连接以获得此类结果?

    name  | Surname | rommate name|roomate surname
    Tom   | Hopkins | Jason       | Lin
    Jason | Lin     | Tom         | Hopkins
    Dylan | Obama   | Peter       | Huang
    Mike  | Rubens  |             |   
    ....  | ....    |  ...        | ....

我想将结果分组为2对,如上所述。有些人没有配对

3 个答案:

答案 0 :(得分:0)

你需要一个左连接。查询将如下:

SELECT p1.name,p1.surname,p2.name as roomate_name,p2.surname as roomate_surname
FROM pairs p1
LEFT JOIN pairs p2 on p1.nr_id=p2.roomate_id
WHERE p1.nr_id <> p1.roommate_id

答案 1 :(得分:0)

这是基本的SQL ...你只需要像这样加入表:

SELECT
   p.name,
   p.surname,
   r.name AS roomate_name,
   r.surname AS roomate_surname
FROM pairs p
LEFT JOIN pairs r ON r.nr_id=p.roomate_id

答案 2 :(得分:0)

为避免同一对夫妇两次,您可以添加条件

SELECT p.name,
       p.surname,
       r.name AS roomate_name,
       r.surname AS roomate_surname
FROM   pairs p
       LEFT JOIN pairs r ON r.nr_id=p.roomate_id
WHERE  p.nr_id > r.nr_id