爲了得到準確的結果集,你正在尋找的查詢是醜陋的,不是很可擴展性(爲舉例來說,如果你有100個usertypes),但在這裏你去
select
u.username,
isnull(ut1.Usertypeid,0) as Type1,
isnull(ut2.Usertypeid,0) as Type2,
isnull(ut3.Usertypeid,0) as Type3,
isnull(ut4.Usertypeid,0) as Type4,
isnull(ut5.Usertypeid,0) as Type5,
isnull(ut6.Usertypeid,0) as Type6
from
users u
left outer join
userstype ut1 on u.userid = ut1.userid and ut1.usertypeid = 1
left outer join
userstype ut2 on u.userid = ut2.userid and ut2.usertypeid = 2
left outer join
userstype ut3 on u.userid = ut3.userid and ut3.usertypeid = 3
left outer join
userstype ut4 on u.userid = ut4.userid and ut4.usertypeid = 4
left outer join
userstype ut5 on u.userid = ut5.userid and ut5.usertypeid = 5
left outer join
userstype ut6 on u.userid = ut6.userid and ut6.usertypeid = 6
編輯
一旦你已經有了你的第10位用戶類型希望常識將會踢進(希望在10日之前),你會想到這不能繼續!
當發生這種情況你會更好,詢問像這樣
select
u.username,
ut..Usertypeid
from
users u
left outer join
userstype ut
on u.userid = ut.userid
然後你會得到一個結果集,看起來像
Username | UserTypeID
---------------------
Joe | 3
Joe | 4
,你會通過在具有循環你的客戶端,但是對你的數據庫服務器和你的理智是一個很好的保證!
什麼數據庫系統? – 2010-03-09 15:20:52
哈哈,已經有6個答案。太多的廚師...... – Codesleuth 2010-03-09 15:25:31
你可能想重新考慮你的查詢這些價值觀的策略。由於您不知道用戶可能具有多少種類型,因此將它們拉到單行中會有問題。簡單地查詢類型並將它們加載到應用程序中可能會更好。這就是說,托馬斯的答案看起來像是一個勝利者。 – 2010-03-09 15:26:42