我有一张表MBR_Role
。现在它有成员ID作为键(主要约束)。对应于每个成员id,可以基于两个指标来存在不同类型的地址。
我有两个指标,Ind1和Ind2。
所以我的表就像 -
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
指标1给出住址,指标2给出办公地址。我希望每个成员的结果中都有这些地址(基于指标)。
所以,我的结果应该是 -
Mbr ID Country City Postal_code Legal Country Legal City Legal Postal_code
1 UK London 11111 Spain Madrid 22222
2 France Paris 44444
有关如何实现这一目标的任何帮助?
答案 0 :(得分:0)
这是一个可能的解决方案(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");
我使用左外连接来处理不存在地址的情况。
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" );
它为您提供期待已久的结果。链接到sqlfiddle http://sqlfiddle.com/#!2/a2ecb/9
无论如何,就像其他人告诉你的那样,我认为如果可能的话,你应该尝试重新设计你的桌子。