如何根据条件在两个表之间进行选择

时间:2013-10-31 08:55:01

标签: mysql

说我有'userBasic','userMan','userWoman'表。

'userBasic'表格中包含名为'userNum'和'gender'的列。

我正在尝试从userMan或userWoman检索基于性别和userBum的userBum数据。

简单地说,

select A.gender, B.nickname from userBasic A, (userman or userwoman) B 
      where A.gender=? and B.userNum=A.userNum;

如果A.gender是男性 - >使用userman B,如果不使用userwoman B。

我怎样才能做到这一点?

1 个答案:

答案 0 :(得分:1)

SELECT 
    ub.gender,
    CASE
        WHEN ub.gender = 'male' THEN um.nickname
        ELSE uw.nickname
    END as nickname
FROM userBasic as ub
LEFT JOIN userMan as um ON ub.userNum = um.userNum
LEFT JOIN userWoman as uw on ub.userNum = uw.userNum

如果您需要选择多个列并且不想执行更多案例陈述

SELECT 
    ub.gender, um.nickname
FROM userBasic as ub
INNER JOIN userMan as um ON ub.userNum = um.userNum
UNION ALL
SELECT 
    ub.gender, uw.nickname
FROM userBasic as ub
INNER JOIN userWoman as um ON ub.userNum = uw.userNum