我正在使用SQL Server,我有两个表
player
:
player guildId
--------------------
a 1
b 2
c 2
d 2
e 1
f 1
g 1
game
:
player gameId
--------------------
a 4
b 1
c 2
d 1
e 3
f 2
g 2
我想创建一个名为view_test的视图,
视图的结果:
select * from view_test where guildId = 2 and gameId = 2
显示
player joined
----------------
b false
c true
d false
select * from view_test where guildId = 2 and gameId = 1
player joined
-----------------
b true
c false
d true
select * from view_test where guildId = 2 and gameId = 3
player joined
----------------
b false
c false
d false
select * from view_test where guildId = 1 and gameId = 4
player joined
----------------
a true
e false
f false
g false
我该怎么做这个SQL?
由于
答案 0 :(得分:1)
尝试这样
select id,case when count(*)=2 then 'true' else
'false' end from (
select id from player where guildId=2
union all
select id from game where gameId=2
) as tt group by id
答案 1 :(得分:1)
尝试此查询我的朋友:
with t as
(select t1.id,t1.guildId,t2.gameId from player t1,game t2 where t1.id = t2.id)
select id,case when gameId = var.VarGameId then 'True'else 'False' end as Joined from t,
(select 1 as VarGameId, 2 as VarGuildId)var where t.guildId = var.VarGuildId;
您可以在我的查询中使用var
之类的内容来更改variables.
答案 2 :(得分:1)
您需要与所有游戏ID交叉加入玩家才能获得所有可能的组合。然后你在游戏桌上查看组合。所以基于以下观点:
select player.player, player.guildid, gameids.gameid,
case when
(
select count(*)
from game
where game.player = player.player
and game.gameid = gameids.gameid
) > 0 then 'true' else 'false' end as joined
from player
cross join (select distinct gameid from game) gameids;
声明
select * from view_test where guildId=2 and gameId=2
会导致
player guildId gameid joined --------------------------------- b 2 2 false c 2 2 true d 2 2 false
答案 3 :(得分:1)
如果您需要检查一个公会(或有限数量)和一个游戏(或有限数量),那么您可以使用这样的查询:
SELECT p.player
, (EXISTS (SELECT player FROM game WHERE player=p.player AND gameId=1)) AS joined
FROM player p
WHERE p.guildId=2
我不会创建一个视图......因为这需要所有玩家与所有不同游戏的完整笛卡尔联盟。我不能确定一旦你从该视图中选择,引擎就能够通过视图优化对基础表和索引的访问,并在合理的时间内给你结果。
视图可能是这样的:
SELECT p.player, p.guildId, g.gameId
, (EXISTS (SELECT player FROM game WHERE player=p.player AND gameId=g.gameId)) AS joined
FROM player p JOIN (SELECT DISTINCT gameId FROM game) g
我必须添加...我不使用SQLServer ......我不确定它是否支持EXISTS子选择表达式。