我有一个名为basicInfo的表,其中包含有关用户的基本信息(例如其性别)。
然后我创建了两个名为userMan和userWoman的表。
使用'性别'在basicInfo中,我想从userMan或userWoman中检索信息。
例如
SELECT
IF(user.gender='male', (man.height, man.location), (woman.height, woman.location)
FROM
basicInfo AS user
LEFT JOIN userMan AS man ON user.id=man.id
LEFT JOIN userWoman AS woman ON user.id=woman.id;
或者
SELECT
CASE WHEN user.gender='male'
THEN man.height, man.location
ELSE woman.height, woman.location
END
FROM
basicInfo AS user
LEFT JOIN userMan AS man ON user.id=man.id
LEFT JOIN userWoman AS woman ON user.id=woman.id;
我有大约17个值放在IF或CASE语句中。我必须使用" user.gender ='男性'"每17个值。
我考虑过使用UNION ALL。但是,我想从userman和userwoman检索的列是不同的。
有没有比使用" user.gender ='男性'"更好的方法。每列?
答案 0 :(得分:2)
在这种情况下,使用union
:
SELECT
user.gender,
man.height,
man.location
FROM
basicInfo AS user
LEFT JOIN userMan AS man ON user.id=man.id
WHERE user.gender='male'
UNION
SELECT
user.gender,
woman.height,
woman.location
FROM
basicInfo AS user
LEFT JOIN userWoman AS woman ON user.id=woman.id;
WHERE user.gender='female'
答案 1 :(得分:2)
除了似乎是最佳选择的UNION ALL
之外,您还可以使用:
SELECT
user.gender,
COALESCE(man.height, woman.height) AS height,
COALESCE(man.location, woman.location) AS location
FROM
basicInfo AS user
LEFT JOIN userMan AS man
ON user.id = man.id
AND user.gender = 'male'
LEFT JOIN userWoman AS woman
ON user.id = woman.id
AND user.gender = 'female'
WHERE -- this can probably be removed
user.gender IN ('male', 'female') ; -- as well