mysql百万数据查询 用什么代替in,该如何处理?

mysql百万数据查询 用什么代替in,该如何处理?,第1张

mysql百万数据查询用exists 代替 in 是一个好的选择:

select num from a where num in(select num from b)

用下面的语句替换:

select num from a where exists(select 1 from b where num=a.num)

SQL查询语句优化方法:

1、应尽量避免在 where 子句中使用!=或<> *** 作符,否则将引擎放弃使用索引而进行全表扫描。

2、对查询进行优化,应尽量避免全表扫描,首先应考虑在 where 及 order by 涉及的列上建立索引。

3、应尽量避免在 where 子句中对字段进行 null 值判断,否则将导致引擎放弃使用索引而进行全表扫描,如:

select id from t where num is null

可以在num上设置默认值0,确保表中num列没有null值,然后这样查询:

select id from t where num=0

4、尽量避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描,如:

select id from t where num=10 or num=20

可以这样查询:

select id from t where num=10

union all

select id from t where num=20

5、下面的查询也将导致全表扫描:(不能前置百分号)

select id from t where name like ‘%c%’

若要提高效率,可以考虑全文检索。

也不知道你指的是什么数据库,对于常用的mysql,sqlserver,oracle 来说in 不是函数而是一个范围运算的关键字,多数在建立约束和对表进行select,update,delete *** 作时候进行一个约束限制和查询,更新,删除的筛选限制。

比如对表users进行查询 *** 作使用in 关键字实现条件限制:

1 select userName from users where address in ('北京','长春','长沙')

2 select username from users where age in (18,19,20)等等。

如果要使用其他手段来代替in 这要根据具体需求来考虑了,如第2条语句可以这样写:

select username from users where age=18 or age=19 or age=20

select username from users where age between 18 and 20

有时也可以使用 not in 从逻辑反实现in 的功能...............

............


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/6179243.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-03-17
下一篇 2023-03-17

发表评论

登录后才能评论

评论列表(0条)

保存