简体   繁体   中英

how to combine 2 mysql rows and get one row

I have a table report_card and,

Sample data as below.

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

and I want result like to get all the rows of mumbai but address is delhi instead of mumbai ? here I have id 1 and 2 have same test_id and 3 and 4 have also. Output like below,

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

A self join like:

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'

What @danblack have written is correct, but to select the orig_id of mumbai you need to write your select like following.

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' 

Edit :

sorry here i change my result on question, can i get all the rows of mumbai but address is delhi instead of mumbai

You can also do it using subquery like following.

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' 

But looking at your data and the expected result, you just need like following

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM