为了得到准确的结果集,你正在寻找的查询是丑陋的,不是很可扩展性(为举例来说,如果你有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