2013-10-31 57 views
0

假設我有'userBasic','userMan','userWoman'表。如何根據條件選擇兩張表

'userBasic'表具有名爲'userNum'和'gender'的列。

我想從userMan或userWoman基於性別和從userBasic表userNum檢索數據。

簡而言之,

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
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 

,或者您需要選擇多列,不希望做更多的case語句

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