2013-08-22 93 views
0

我有一個複雜的SQL查詢問題。Mysql:左連接變量表

我有3個表: 用戶, user_type1, user_type2

我想請根據自己的類型的用戶的詳細信息。 我試着用CASE爲LEFT JOIN動態選擇表名,但是我失敗了。 我也嘗試過使用UNION,但似乎列必須相同。

是工作的唯一辦法就是加入兩個表,但後來的結果也包含錯誤的表中的所有空值...

我正在尋找一種方法來擺脫這些錯誤的字段,或者只爲左右連接做好表格。

這裏是我當前的代碼:

SELECT 
    user.*, 
    user_type1.*, 
    user_type2.* 
FROM user 
LEFT JOIN user_type1 
    ON user_type1.user_id = user.id 
LEFT JOIN user_type2 
    ON user_type2.user_id = user.id 
AND user.id = 1 

通常我只會做非常簡單的查詢,所以我有點糊塗了。謝謝,如果你能幫助我。

編輯: 主表是用戶,只有2個字段:ID和類型。

其他表包含有關用戶的詳細信息。 user_type1適用於人。這些字段是名稱,年齡,...

user_type2是針對公司。這些字段是名稱,法律形式,僱員人數,...

所以我只知道用戶表中的ID,我需要獲得良好表的字段。

如果user.id是1和user.type是TYPE1,我希望MySQL得到user_type1表中的所有字段...

+0

user_type1_id,它是一個小姐拼? user_type1.id –

+0

@Deepanshu是的,對不起。它是user_type1.user_id。 – FLX

回答

0

則必須選擇不null作爲列:

SELECT 
    user.*, 
    user_type1.*, 
    user_type2.* 
FROM user 
LEFT JOIN user_type1 
    ON user_type1_id = user.id 
LEFT JOIN user_type2 
    ON user_type2.user_id = user.id 
AND user.id = 1 
AND table.column_name IS NOT NULL 
2

你可以試試這個: -

select * 
from user, user_type1, user_type2 
where user_type1.user_id = user.id and user_type2.user_id = user.id AND user.id = 1