mysql 中 in 的用法

Posted 乔木晨子

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 中 in 的用法相关的知识,希望对你有一定的参考价值。

1. select * from student s where s.id in (20,30);

查询id是20或者是30,等同于select * from student s where s.id = 20 or s.id = 30;

2.select * from student s where s.id in (select age from student);

查询id是age数组里面的,单个字段只能in查询结果是单行的。

很明显后面括号的 select age from student 查出来只有age这一列,假如括号的查询查出来的age是下面图列

那么此时查询就等价于select * from student s where s.id in (64,57,32,24,35,55);

3.select * from student s where (s.class , s.score) in (select class , max(score) from student group by class)

既然能单个字段in单行结果,那么多个字段就能in多行结果了

这个sql表示:查询每个班级中分数最高的学生的所有数据

注意,此时的name和class是不会错位的,你本来就是按着匹配的class和score去in匹配class、score的结果集,所以数据不会出错的。

如果你写成这样:

select * from student s where s.class in (select class from student group by class ) and s.score in (select max(score) from student group by class);

就把class和score的关系分开了,分开后就可能出现结果列错位的情况,可能名字和他的分数对不上。

在Mysql5.0 中In 用法的疑惑

SELECT * FROM A where A.bigclass in(select arrchild from B) 这样子为什么查不到数据,但是写成
SELECT * FROM A where A.bigclass in(1,2,35,5) 这样子就可以。

注:select arrchild from B 的查询结果是一条记录内容是一字符串(1,2,35,5)

select arrchild from B 的查询结果是一条记录内容是一字符串(1,2,35,5)
这种情况下,

执行
SELECT * FROM A where A.bigclass in(select arrchild from B)
相当于执行
SELECT * FROM A where A.bigclass in( '1,2,35,5' )
结果肯定是没有。

假如你的
select arrchild from B 的查询结果是
1
2
35
4
这样的 4 行数据。
那么
SELECT * FROM A where A.bigclass in(select arrchild from B)
就等价于
SELECT * FROM A where A.bigclass in(1,2,35,5)

如果
select arrchild from B 的查询结果是一条记录内容是一字符串(1,2,35,5)
又要实现
SELECT * FROM A where A.bigclass in(1,2,35,5) 的效果。

一个变通的办法是:
SELECT * FROM A
where
INSTR ( CONCAT ( ',' , (select arrchild from B) , ',' ),
CONCAT (',' , A.bigclass , ',' ) ) > 0追问

啊,我明白了
SELECT * FROM A where A.bigclass in(1,2,35,5) 这里面的(1,2,35,5) 相当于多个值。
而(select arrchild from B 的查询结果有且只有一条记录且内容是就是 "1,2,35,5")相当于一个值。

参考技术A 使用的时候他会将select arrchild from B查询出来的每条记录当做一个整体
SELECT * FROM A where A.bigclass in(select arrchild from B) 这个相当于
SELECT * FROM A where A.bigclass in( ‘1,2,35,5’ ) ----所以查不出来
------------------------------
arrchild
1,2,35,5
------------------------------

想要下面的结果,
select arrchild from B这个查询出来的结果要是这样的
----------------------------------------
arrchild
1
2
35
5
----------------------------------------追问

注:select arrchild from B 的查询结果有且只有一条记录且内容是就是 "1,2,35,5"

参考技术B 不是查不到,应该是速度很慢。如果可以的话尽量使用=来代替in语句,myql的in语句貌似没有优化过,效率很低的

以上是关于mysql 中 in 的用法的主要内容,如果未能解决你的问题,请参考以下文章

mysql 中find_in_set()和in()用法比较

sql中的like用法

MYSQL中in的用法

sql in用法

关于sql查询中的like用法疑问?

MySQL中的SQL Mode及其作用