我有以下表格:
1. club_members (id, type, name)
2. male_members (name, age, location)
3. female_members (name, age, location)
4. senior_members (name, age, location)
我需要根据从第一个表中检索的类型选择这3个表中的一个。
与type=male
一样,我会从male_members中选择,依此类推。
所以我想写一个类似于
的查询select type, name , age , location from club_members , (2/3/4 table) where id=X ...
如何编写此类查询。
可能正在使用 if/else
或 case
语句
答案 0 :(得分:4)
假设名称为表格之间的链接。
select
C.type as Type,
COALESCE(m.name, f.name, s.name) AS MemberName,
COALESCE(m.age, f.age, s.age) AS MemberAge,
COALESCE(m.location, f.location, s.location) AS Location
from club_members C
left join male_members M on C.name=M.name and C.type='Male'
left join female_members F on C.name=F.name and C.type='Female'
left join senior_members S on C.name=S.name and C.type='Senior'
where C.id='Your value'