问题
I have a feeling CASE should be used here but I am not sure. I'm trying to take the sex (m/f) from the general table and depending on the sex, get the build from the corresponding table. For example, when the sex is m, the query should know that by going to the males table and selecting the male_build. I put together an output along with a sample query to give an idea of what I'm trying to accomplish:
members table
member_id | member_name
------------------------
1 Herb
2 Karen
3 Megan
4 Pablo
males table
male_id | member_id | male_build
---------------------------------
1 1 muscular
2 4 fat
females table
female_id | member_id | female_build
-------------------------------------
1 2 thin
2 3 fat
general table
general_id | member_id | sex
-----------------------------
1 1 m
2 2 f
3 3 f
4 4 m
The output should be like this:
1. Herb is a muscular male.
2. Karen is a thin female.
3. Megan is a fat female.
4. Pablo is a fat male.
-> query = "SELECT g.general_id, g.member_id, g.sex,
(CASE when g.sex=m THEN SELECT ma.male_build AS build
FROM males ma WHERE ma.member_id=g.member_id,
CASE when g.sex=f THEN SELECT fe.female_build AS build
FROM females fe WHERE fe.member_id=g.member_id),
m.member_name
FROM members m
JOIN members m ON g.member_id=m.member_id
WHERE g.sex='m' OR g.sex='f'";
Looking for an efficient query for this task.
回答1:
When you are having to do queries like this, it is a good idea to rethink your database design schemas. That being said, this should work:
SELECT mem.*, g.*, coalesce(m.male_build, f.female_build) as build
from members_table mem
inner join general g on mem.meber_id = g.member_id
left join males m on mem.member_id = m.member_id
left join females f on mem.member_id = f.member_id
回答2:
Select M.member_name + ' is a '
+ gender_attributes.sex_name
+ ' '
+ gender_attributes.build
From members As M
Join general_table As G
On G.member_id = M. member_id
Join (
Select 'm' As sex, 'male' As sex_name, male_id as id, member_id, male_build As build
From males_table
Union All
Select 'f' As sex, 'female', female_id, member_id, female_build
From females_table
) As gender_attributes
On gender_attributes.sex = G.sex
And gender_attributes.member_id = M.member_id
回答3:
I'd just have a build_types
table and a foreign key on your members
table. It may be an edge case, but you can get muscular women, and thin guys.
来源:https://stackoverflow.com/questions/10353813/mysql-retrieve-row-value-from-different-table-depending-on-value-of-row-in-a-t