1

我有下表

Table User
UserID         Name
1              Om
2              John
3              Kisan
4              Lisa
5              Karel

Table Game
Games          Players
Golf           1,3,5
Football       4

我写了查询:

Select UserId, 
Name from User 
Where UserID IN 
    (Select Players from Game where Games='Golf')

Result:
~~~~~~~
0 Rows

当我在语句中直接为 In 子句指定值时,上面的查询不会返回任何结果,但它运行良好。

Select UserId, Name 
from User 
Where UserID IN (1,3,5)

Result:
~~~~~~~
UserID         Name
1              Om
3              Kisan
5              Karel
3 rows

但是,当我使用 Football 更改第一个查询中的条件时:

Select UserId, Name 
from User 
Where UserID IN 
    (Select Players 
     from Game 
     where Games='Football'). 

这将返回以下结果:

UserID         Name
4              Lisa
1 row

我该如何解决,以便我的第一个查询返回正确的结果?

我想我走错了方向。帮帮我!

4

3 回答 3

5

这就是在字段中存储逗号分隔值的结果。现在你必须拆分它,使用,说这个功能并做类似的事情

Select User.UserId, User.Name from User 
inner join splitstring((Select Players from Game where Games='Golf')) a
on User.UserID = a.Name

但考虑将您的桌子“游戏”设计更改为

Games          Players
Golf           1
Golf           3
Golf           5
Football       4

然后你可以做简单的

Select User.UserId, User.Name
from User inner join Game
on User.UserID = Game.Players
Where Game.Games = 'Golf'

没有任何附加功能。

于 2013-10-10T17:06:32.237 回答
2

您的第一个查询转换为:

Select UserId, Name 
from User 
Where UserID IN (`1,3,5`)

请注意,它是 ID 的字符串表示形式,而不是第二个查询中的逗号分隔列表。

有很多Split函数是为这个场景编写的。

您可以这样使用其中之一:

DECLARE @PlayersCsv NVARCHAR(MAX)
Select @PlayersCsv = Players from Game where Games='Golf'

Select UserId, 
Name from User 
Where UserID IN 
    (Select Value FROM dbo.Split(@PlayersCsv, ','))
于 2013-10-10T17:03:19.497 回答
0
DECLARE @xml AS xml
SET @xml = (SELECT cast('<X>'+(''+replace(players,',' ,'</X><X>')+'</X>') AS xml)
            FROM Game WHERE Games='Golf')
SELECT UserId, Name 
FROM User
WHERE UserID IN
(SELECT N.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as T(N))

SQL小提琴结果

| USERID |  NAME |
|--------|-------|
|      1 |    Om |
|      3 | Kisan |
|      5 | Karel |
于 2013-10-10T17:50:12.683 回答