簡體   English   中英

Mysql:左邊連接變量表

[英]Mysql : left join on variable table

我有一個復雜的SQL查詢的問題。

我有3個表:user,user_type1,user_type2

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

唯一有效的方法是連接兩個表,但結果還包含來自錯誤表的所有空值...

我正在尋找一種擺脫這些錯誤字段的方法,或者只為好桌子做LEFT JOIN。

這是我目前的代碼:

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和Type。

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

user_type2適用於公司。 這些字段是名稱,法律形式,員工人數,......

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

如果user.id為1且user.type為type1,我希望mysql從user_type1表中獲取所有字段...

你可以試試這個: -

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

那么你必須選擇非空的列:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM