【问题标题】:Very slow query to find all records without a relationship查找所有没有关系的记录的速度非常慢
【发布时间】:2018-12-06 07:53:11
【问题描述】:

我试图找出所有ordersusers

到目前为止,我已经尝试了以下方法:

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 名客户和 30,000 多个订单。有没有更有效的方法来做到这一点?

【问题讨论】:

  • 您尝试过索引吗?

标签: mysql left-join relationship not-exists


【解决方案1】:

您需要将子查询限制为仅查看 user_id。还要确保 user_id 已编入索引。

Alter table orders add index(user_id)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-23
    • 2017-10-21
    相关资源
    最近更新 更多