简体   繁体   中英

MySQL query - join different tables based on a precondition (value retrieved from a different table)

I have following tables :

1. club_members (id, type, name)
2. male_members (name, age, location)
3. female_members (name, age, location)
4. senior_members (name, age, location)

I need to select 1 of these 3 tables based on type retrieved from 1st table. like for type=male , i will select from male_members and so on.

so i want to write a query similar to

select type, name , age , location from club_members , (2/3/4 table) where id=X ...

how to write such query.

may be using if/else or case statements

Assuming Name as the link between tables.

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM