Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 优化sql双“Not in”子句_Mysql_Sql_Database - Fatal编程技术网

Mysql 优化sql双“Not in”子句

Mysql 优化sql双“Not in”子句,mysql,sql,database,Mysql,Sql,Database,我有以下疑问: select * from table_2 where user_1 not in (select user_id from users) or user_2 not in (select user_id from users) 问题是执行需要很长时间。这些表格有数百万条记录。是否有任何优化可以用于查询 首先,将这些内容重写为不存在的内容。这通常具有更好的性能: select t2.* from table_2 t2 where not exists (select 1

我有以下疑问:

select * from table_2 
where 
user_1 not in (select user_id from users) or 
user_2 not in (select user_id from users)
问题是执行需要很长时间。这些表格有数百万条记录。是否有任何优化可以用于查询

首先,将这些内容重写为不存在的内容。这通常具有更好的性能:

select t2.*
from table_2 t2
where not exists (select 1 from users u where u.user_id = t2.user_1) or 
      not exists (select 1 from users u where u.user_id = t2.user_2);
更重要的是,如果usersuser\u id还不存在,请在其上创建一个索引。

首先,将其重写为不存在。这通常具有更好的性能:

select t2.*
from table_2 t2
where not exists (select 1 from users u where u.user_id = t2.user_1) or 
      not exists (select 1 from users u where u.user_id = t2.user_2);
更重要的是,如果usersuser\u id不存在,请在其上创建索引。

您应该尝试以下操作:

select * from table_2
LEFT JOIN `users` AS u ON u.user_id = table_2.user_1
LEFT JOIN `users` AS u2 ON u2.user_id = table_2.user_2
WHERE u.user_id is NULL and u2.user_id is NULL
你应该试试这个:

select * from table_2
LEFT JOIN `users` AS u ON u.user_id = table_2.user_1
LEFT JOIN `users` AS u2 ON u2.user_id = table_2.user_2
WHERE u.user_id is NULL and u2.user_id is NULL
这应该表现得更好


这应该会执行得更好。

此查询将返回user_1和/或user_2不在users表中的所有行

select * from table_2 t1
where (select count(*) from users u where user_id in(t1.user_1,t1.user_2)) < 2

此查询将返回user_1和/或user_2不在users表中的所有行

select * from table_2 t1
where (select count(*) from users u where user_id in(t1.user_1,t1.user_2)) < 2

我有一个问题,如果我选择字段对字段而不是t2,会提高性能。*??示例:选择t2.a,t2。b@kbworkshop . . . 如果选择相同的字段,则不会影响性能。如果您打算在视图、存储过程或作业(例如)中以任何方式重用此查询,建议显式选择字段。我有一个问题,如果我选择字段对字段而不是t2,则会提高性能。*??示例:选择t2.a,t2。b@kbworkshop . . . 如果选择相同的字段,则不会影响性能。如果您打算以任何方式重用此查询(例如,如果它要进入视图、存储过程或作业),建议显式选择字段。这仅返回用户表中未定义user_1和user_2的记录。而原始查询显示了其中一个用户不存在的所有记录。尝试u.user_id为NULL或u2.user_id为NULL的位置。这仅返回users表中未定义user_1和user_2的记录。而原始查询显示了其中一个用户不存在的所有记录。尝试u.user\u id为NULL或u2.user\u id为NULL的位置。