2

我有一个名为 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 语句中。我必须为每 17 个值使用“user.gender='male'”。

我考虑过使用 UNION ALL。但是,我想从 userman 和 userwoman 检索的列是不同的。

有没有比对每一列使用“user.gender='male'”更好的方法?

4

2 回答 2

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'
于 2013-11-06T06:52:58.080 回答
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
于 2013-11-06T07:02:51.060 回答