2016-10-18 38 views
0

我有表 用戶(用戶名,密碼,全名,用戶類型)強制不相交:美麗的查詢?

有4種類型的用戶的模式和對每個存在與特定類型的附加屬性的表:

  • 個人(用戶名(國外),教育,work_since)
  • 公司*(用戶名(國外),總部,辦公室,num_employees)
  • 和一對夫婦更多...

在用戶的所有附加表中可能只有1條記錄。

我需要根據用戶類型顯示用戶表和附加屬性表中的所有用戶信息。

首先想到的是首先查詢用戶表,然後根據返回的類型查詢相關表中的一個...但這會太多查詢,所以我想知道,是嗎?可能在單個查詢中做到這一點?

回答

1

使用left join

select u.*, 
     (case when i.username is not null then 'individual' 
      when c.username is not null then 'corporation' 
     end) as usertype, 
     i.education, i.work_since, 
     c.headquarters, c.office, c.num_employees 
from users u left join 
    individual i 
    on i.username = u.username left join 
    corporation c 
    on c.username = u.username; 
+0

戈登,非常感謝你!另一個快速的問題..有沒有辦法只從結果中投影NOT NULL列? –

+0

@KonstantinRybakov。 。 。我不是100%確定的,我知道你的意思。你可以使用'where'子句過濾掉'NULL'值。 –