Show Nested query result in outer query

本小妞迷上赌 提交于 2019-12-12 02:27:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!