繁体   English   中英

SQL 使用具有多个值的 Where 子句的语句

[英]SQL Statement using Where clause with multiple values

我有一个包含多行的表,其中包含以下字段:

PersonName SongName Status

我想使用从多选列表框中选择的名称,我可以从中检索值,然后执行一个 where 子句,以便它显示所选人员都可以播放的歌曲名称,因此状态是完整的。

例如:

 PersonName      SongName    Status 
 Holly           Highland    Complete
 Holly           Mech        Complete 
 Ryan            Highland    Complete

如果我从列表框中输入 select Holly 和 Ryan 并按下按钮,查询应该只显示 Highland,因为这是他们都知道的。

试试这个:

select songName from t
where personName in ('Ryan', 'Holly')
group by songName
having count(distinct personName) = 2

人数应与人数相符。 如果您还需要 Status 为Complete ,请使用此where子句而不是前一个:

where personName in ('Ryan', 'Holly') and status = 'Complete'
SELECT PersonName, songName, status
FROM table
WHERE name IN ('Holly', 'Ryan')

如果您使用的是参数化存储过程:

  1. 传入逗号分隔的字符串
  2. 使用特殊的 function 将逗号分隔的字符串拆分为表值变量
  3. 使用INNER JOIN ON t.PersonName = newTable.PersonName使用包含传入名称的表变量
Select t1.SongName
From tablename t1
left join tablename t2
 on t1.SongName = t2.SongName
    and t1.PersonName <> t2.PersonName
    and t1.Status = 'Complete' -- my assumption that this is necessary
    and t2.Status = 'Complete' -- my assumption that this is necessary
    and t1.PersonName IN ('Holly', 'Ryan')
    and t2.PersonName IN ('Holly', 'Ryan')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM