如何合并2 mysql行并获得一行

时间:2019-02-28 06:04:27

标签: mysql sql database join self-join

我有一张桌子report_card

采样数据如下。

report_id  orig_id   test_id        name     address
------------------------------------------------------
1           JH06E     IN2001         xyz      delhi
2           HL789     IN2001         abc      mumbai
3           ZPYNR     IN2002         pqr      mumbai
4           5R4HJ     IN2002         mno      delhi

,我想要结果像得到孟买的所有行,但地址是德里而不是孟买? 在这里,我的ID 1和2具有相同的test_id,而3和4也具有相同的ID。输出如下所示,

report_id  orig_id   test_id        name     address
------------------------------------------------------
 2           HL789     IN2001         abc      delhi
 3           ZPYNR     IN2002         pqr      delhi

2 个答案:

答案 0 :(得分:2)

自我加入,例如:

SELECT t1.report_id, t1.orig_id, t1.test_id, t1.name, t2.address
FROM report_card t1
JOIN report_card t2
  ON t1.test_id = t2.test_id
WHERE
  t1.address = 'mumbai' AND
  t2.address = 'delhi'

答案 1 :(得分:2)

@danblack写的是正确的,但是要选择orig_id的孟买,您需要像下面这样写选择。

SELECT t1.report_id, 
       t2.orig_id, 
       t1.test_id, 
       t1.name, 
       t1.address 
FROM   mytable t1 
       INNER JOIN mytable t2 
               ON t1.test_id = t2.test_id 
WHERE  t1.address = 'delhi' 
       AND t2.address = 'mumbai' 

编辑

  

对不起,在这里我有疑问地更改了我的结果,我可以获取所有的行吗?   孟买,但地址是德里,而不是孟买

您还可以使用如下所示的子查询来做到这一点。

SELECT t1.report_id, 
       t1.orig_id, 
       t1.test_id, 
       t1.name, 
       (SELECT address 
        FROM   mytable m 
        WHERE  m.test_id = t1.test_id 
               AND m.address = 'delhi' 
        LIMIT  1)AS address 
FROM   mytable t1 
WHERE  t1.address = 'mumbai' 

但是查看您的数据和预期结果,您只需要关注以下内容

SELECT t1.report_id, 
       t1.orig_id, 
       t1.test_id, 
       t1.name, 
       'delhi' address 
FROM   mytable t1 
WHERE  t1.address = 'mumbai'