非常慢的查询来查找没有关系的所有记录

hpcdzsge  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(249)

我想找到所有的 users 他们没有 orders .
到目前为止,我尝试了以下方法:

select * from `users` where not exists 
(select * from `orders` where `users`.`id` = `orders`.`user_id`)

我还尝试了以下方法:

select users.*, count(distinct orders.reference) as orders_count from `users` 
left join `orders` on `users`.`id` = `orders`.`user_id` 
group by `users`.`id` having orders_count = 0

但是,这两种查询运行速度都非常慢。大约有5000个客户和30000多个订单。有没有更有效的方法?

oewdyzsn

oewdyzsn1#

您需要将子查询限制为只查看用户id。还要确保用户id已编入索引。

Alter table orders add index(user_id)

Select * from users where id NOT IN(select user_id from 
orders)

相关问题