问题
I have a table say MBR_Role
. Now it has member id as key (Primary constraint). Correspondng to each member id, there can be different type of adresses based on two indicators.
I have two indicators, Ind1 and Ind2.
So my table is like -
Mbr ID Ind1 Ind2 Country City Postal_code
1 Y N UK London 11111
1 N Y Spain Madrid 22222
1 N N US New York 33333
2 Y N France Paris 44444
Indicator 1 gives residential address, Indicator 2 gives office address. I want both these addresses in the result for each member (based on indicator).
So, my result should like -
Mbr ID Country City Postal_code Legal Country Legal City Legal Postal_code
1 UK London 11111 Spain Madrid 22222
2 France Paris 44444
Any help on how to achieve this ?
回答1:
Here is a possible solution (MySQL)
CREATE TABLE MBR_Role(
Mbr_ID INT,
Ind1 VARCHAR(1),
Ind2 VARCHAR(1),
Country VARCHAR(30),
City VARCHAR(30),
Postal_code VARCHAR(30));
INSERT INTO MBR_Role VALUES (1, "Y", "N", "UK", "London", "11111");
INSERT INTO MBR_Role VALUES (1, "N", "Y", "Spain", "Madrid", "22222");
INSERT INTO MBR_Role VALUES (1, "N", "N", "US", "New York", "33333");
INSERT INTO MBR_Role VALUES (2, "Y", "N", "France", "Paris", "44444");
I use left outer joins to handle cases where adress is not present.
select a.Mbr_ID,
b.Country, b.City, b.Postal_code,
c.Country as legal_country, c.City as legal_city, c.Postal_code as legal_Postal_code
from (select distinct Mbr_ID from MBR_Role) as a
LEFT OUTER JOIN MBR_Role b ON (b.Mbr_ID = a.Mbr_ID AND b.Ind1 = "Y" AND b.Ind2 = "N" )
LEFT OUTER JOIN MBR_Role c ON (c.Mbr_ID = a.Mbr_ID AND c.Ind1 = "N" AND c.Ind2 = "Y" );
It gives you the awaited result. Link to sqlfiddle http://sqlfiddle.com/#!2/a2ecb/9
Anyway like other told you, I think you should if possible try to redesign your table.
来源:https://stackoverflow.com/questions/22906364/show-nested-query-result-in-outer-query