SQL 使用一张表中的 where 选择多行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8611843/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQL Select multiple rows using where in one table
提问by Munkhjin
I have a table named "Student".
我有一个名为“学生”的表。
Student
id | name | age
1 | john | 10
2 | Hyman | 10
3 | jerry| 10
I wanna select 1 and 2 rows. I wrote that Select * from Student where name=john and name=Hyman
But return "Empty Set".
How do i do it. Help me.
我想选择 1 和 2 行。我写了Select * from Student where name=john and name=Hyman
但返回“空集”。我该怎么做。帮我。
回答by
select *
from student
where name in ('john', 'Hyman')
Or
或者
select *
from student
where name = 'john'
or name = 'Hyman'
回答by MatBailie
You need an OR
rather than an AND
.
你需要一个OR
而不是一个AND
.
Whatever conditions your write, it checks them all against each record. As no single record has both name = 'john'
AND name = 'Hyman'
they all fail.
无论您的写入条件如何,它都会根据每条记录检查它们。由于没有一条记录同时具有name = 'john'
ANDname = 'Hyman'
它们都失败了。
If, instead, you use OR
...
- The 1st record yields TRUE OR FALSE
which is TRUE.
- The 2nd record yields FALSE OR TRUE
which is TRUE.
- The 3rd record yields FALSE OR FALSE
which is FALSE.
相反,如果您使用OR
...
- 第 1 条记录产生的TRUE OR FALSE
结果为 TRUE。
- 第二条记录产生的FALSE OR TRUE
结果是 TRUE。
- 第 3 条记录的收益FALSE OR FALSE
率为 FALSE。
Select * from Student where name='john' OR name='Hyman'
Or, using a differnt way of saying it all...
或者,用不同的方式来表达这一切......
SELECT * FROM Student WHERE name IN ('john', 'Hyman')
回答by Russell
Use single quotes to surround your values, plus use and instead of or:
使用单引号将您的值括起来,并使用 and 代替 or:
where name='john' or name = 'Hyman'
回答by Tamkeen
try this one.
试试这个。
declare @names varchar(100)
set @names='john,Hyman'
Select * from Student
where charIndex(',' + rtrim(cast(name as nvarchar(max))) + ',',',' +isnull(@names,name) +',') >0