如何使用条件来检查 2 件事,当 2 为真时,它会提供信息

how to use condition to check 2 things and when the 2 are true, it give an information

我编写了一个代码来告诉我有多少玩家在使用特定的角色扮演游戏 class(所以我检查了第一手剑和二手剑,它应该告诉我100级以上双手持剑玩家的姓名和等级,代码如下:

declare @level varchar(100)
set @level=80

select level,name from characters c
inner join items i on i.characterId=c.characterId
where
( level>@level AND equipSlot=5 and ( 
itemId=2002 OR --short sword
itemId=2005 OR --steel rapier
itemId=2010 OR --volt sword
itemid=2012 OR --goblin knife
itemId=2017 OR --crimson sword
itemId=2026 OR --tree splitter sword
itemId=2031 OR --sea king sword
itemId=2034 OR --acrodont blade
itemid=2054 OR --halloween sword
itemId=2059 --stinger
))
and
(level>@level and equipSlot=6 and ( 
itemId=2002 OR --short sword
itemId=2005 OR --steel rapier
itemId=2010 OR --volt sword
itemid=2012 OR --goblin knife
itemId=2017 OR --crimson sword
itemId=2026 OR --tree splitter sword
itemId=2031 OR --sea king sword
itemId=2034 OR --acrodont blade
itemid=2054 OR --halloween sword
itemId=2059 --stinger
))
ORDER by level desc

所以我检查第一手(equipslot=6),检查是否装备了一把可用的剑,然后如果第二只手(equipslot=5)也有一把剑,这意味着这个人正在使用2把剑class.

但是当我在 2 个括号之间放置 and 时它没有任何作用。 当我使用 or 时,它显示所有人都在第一手使用剑,所以没有使用 2 把剑的人也会出现。

我不知道我怎么能 select 玩家名字和等级一次(因为当他们使用 2 把剑时,他们的名字出现两次而不是一次),所以检查他们的手,如果他们双手持剑,亮出名字和等级

您想检查属于给定字符的 items 是否满足条件,这表明聚合:

select c.name 
from characters c
inner join items i on i.characterId=c.characterId
where 
    i.level > @level
    and i.equipslot in (5, 6)
    and i.itemid in (2002, 2005, 2010, 2012, 2017, 2026, 2031, 2034, 2054, 2059)
group by c.name
having count(distinct equipslot) = 2

如果想显示每手牌的等级,可以这样做:

select c.name, 
    max(case when i.equipslot = 5 then level end) level_hand_5,
    max(case when i.equipslot = 6 then level end) level_hand_6
from characters c
inner join items i on i.characterId=c.characterId
where 
    i.level > @level
    and i.equipslot in (5, 6)
    and i.itemid in (2002, 2005, 2010, 2012, 2017, 2026, 2031, 2034, 2054, 2059)
group by c.name
having count(distinct equipslot) = 2

备注:

  • 在 multi-table 查询中,为每个列加上它所属的 table 前缀是一个好习惯;我做了一些您可能需要查看的假设

  • in 可以方便地缩短多个 or 条件