我有一种感觉CASE应该在这里使用,但我不确定。我试图从普通表中取出性别(m / f),并根据性别,从相应的表中获取构建。例如,当性别是m时,查询应该知道通过转到男性表并选择male_build。我将输出和示例查询放在一起,以便了解我正在尝试完成的任务:
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
输出应该是这样的:
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'";
寻找有效查询此任务。
答案 0 :(得分:1)
当你不得不做这样的查询时,最好重新考虑你的数据库设计模式。话虽如此,这应该有效:
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
答案 1 :(得分:0)
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
答案 2 :(得分:0)
我的build_types
表上只有一个members
表和一个外键。这可能是一个边缘案例,但你可以得到肌肉发达的女性和瘦弱的男性。