Using single query to retrieve multivalued attribute by joining two tables without causing duplication of fields in mysql

StackOverflow https://stackoverflow.com/questions/3717714

  •  02-10-2019
  •  | 
  •  

Question

Table 1 :
QUERY: Create table client ( applicationNo int primary key, name varchar(20) );

Insert statement: Insert into client values (1,'XYZ'),(1,'ABC'),(1,'DEF');

applicationNo   |   name  
    1           |   XYZ  
    2           |   ABC  
    3           |   DEF  

Table 2:
Query : Create table client ( applicationNo int, phoneNo Bigint, foreign key (applicationNo) references client (applicationNo), primary key(applicationNO,phoneNo) );

Insert into phoneNO values (1,999999),(1,888888),(2,777777),(3,666666),(3,555555);

applicationNo | phoneNo
1             |   999999
1             |   888888
2             |   777777
3             |   666666
3             |   555555

Can I retrieve the tuples by joining both the tables in such a way that get the following output, but using single query, also I'm using mysql 5.1

applicationNo |   name | phoneNo1 | phoneNo2 
1             |   XYZ  |  999999  |   88888
2             |   ABC  |  77777   |   Null
3             |   DEF  |  66666   |   555555

Edited : extra information
I tried using this something called cross tab .But I'm not able to use the totalPhoneNo inside the case statement

SELECT applicationNo,count(phoneNo) as totalPhoneNo,  
SUM(CASE WHEN totalPhoneNo= 1 THEN phoneNO ELSE Null END) AS phoneNo1,  
SUM(CASE WHEN totalPhoneNO = 2 THEN phoneNo ELSE Null END) AS phoneNo2  
FROM phoneNO GROUP BY applicationNo;
Was it helpful?

Solution

Try:

select c.applicationNo, 
       max(c.name) name,
       max(p.phoneNo) phoneNo1,
       case 
           when max(p.phoneNo) = min(p.phoneNo) then NULL 
           else min(p.phoneNo) 
       end phoneNo2
from client c
left join phoneNo p on c.applicationNo = p.applicationNo
group by c.applicationNo

OTHER TIPS

Here is is for MSSQL. Does this convert nicely?

With phones (ApplicationNo, PhoneNo, Instance) as
(Select ApplicationNo, PhoneNo,
  Row_Number OVER (Partition By ApplicationNo) as RowNum)
Select client.ApplicationNo, client.Name, 
  p1.PhoneNo as phoneNo1, p2.PhoneNo as phoneNo2
From client
  Left Join phones p1 on client.ApplicationNo=p1.ApplicationNo as p1.RowNum=1
  Left Join phones p2 on client.ApplicationNo=p2.ApplicationNo as p2.RowNum=2

use subselects with limit clauses. the first subselect picks the first phone the other the second.

select ApplicationNo,
(SELECT phoneno FROM phones where phones.applicationno=app.ApplicationNo order by phoneno LIMIT 0, 1)as phone1,
(SELECT phoneno  FROM phones where phones.applicationno=app.ApplicationNo order by phoneno LIMIT 1, 1)as phone2
from application app
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top