我正在尝试为现有表数据编写查询。TABLE_A 和 TABLE_B 有 1 条记录,但 TABLE_C 有 2 条记录。一个用于家庭地址,另一个用于工作地址。
因此,以下查询返回 2 条记录。我试图从 2 条记录中只获得 1 条记录。
如果 CITY 为 NULL,则 address_type = 1(Home) 的 state_id 为 null 然后获取 Work(address_type = 2) 地址。如果两者都为空,则获取“家庭”地址。实现此功能的最佳方法是什么。
谢谢你的任何建议。
select a.A_ID, a.B_ID, a.A_DESC, b.first_name, b.last_name, c.address_type, c.city, c.state
from table_A a
left join table_B b on b.B_ID = a.B_ID
left join table_C c on c.B_id = b.B_id
where a.A_ID = 10
表_A
A_ID int
B_ID int
A_Desc varchar(20)
表_B
B_ID int
first_name varchar(30)
last_name varchar(30)
表_C
C_ID int
B_ID int
address_type int
city varchar(50)
state int
结果:
A_ID B_ID A_DESC first_name last_name address_type city state
--------------------------------------------------------------------------------
10 200 test_ name1 name_last 1 NULL NULL
10 200 test_ name1 name_last 2 City_test 2
我想要这个最终结果
A_ID B_ID A_DESC first_name last_name address_type city state
--------------------------------------------------------------------------------
10 200 test_ name1 name_last 2 City_test 2