由于 IN 子句,Mysql 查询变慢了.任何可能的替代方案


Mysql Query getting slower due to IN clause. Any possible alternatives?

我有2个mysql表"存储(id,name,imageurl("和"favorites(person,storeid("。

一切都很好。但随着数据的增加,它变得越来越慢。我认为这主要是由于查询中的"IN"。有没有办法使这个查询在执行中更智能?

SELECT id,name,imageurl FROM store WHERE id IN 
(SELECT storeid FROM favorites WHERE person='rhino' AND storeid>100000)

提前谢谢。

使用连接语法。此处无需子查询

SELECT store.id, store.name, store.imageurl
  FROM store
  JOIN favorites ON store.id = favorites.storeid
  WHERE favorites.person = 'rhino' AND store.id > 100000

您应该使用EXPLAIN来了解查询性能。

这是另一种方法

看起来您可以直接查找而不是IN。像这样:

SELECT s.id, s.name, s.imageurl 
FROM store s, favorites f 
WHERE f.person='rhino' AND f.storeid>100000 AND f.storeid=s.id

这种方法避免了JOIN,这也可能是昂贵的。

SELECT 
store.id,
store.name,
store.imageurl
FROM store
INNER JOIN favorites
    ON store.id = favorites.storeid
    AND favorites.person = 'rhino'
WHERE store.id > 100000

这基本上是关于优化查询 - 在这种情况下,JOIN 比嵌套选择更好。

您可能还需要确保在favorites.storeidfavorites.person上具有索引,因为您具有 JOIN 和 WHERE 条件。