Mysql 由于 IN 子句,查询速度变慢。任何可能的选择?
Mysql Query getting slower due to IN clause. Any possible alternatives?
我有 2 个 mysql 表 "store (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 优于嵌套 select。
您可能还想确保在 favorites.storeid
和 favorites.person
上有索引,因为它们有 JOIN 和 WHERE 条件。
我有 2 个 mysql 表 "store (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 优于嵌套 select。
您可能还想确保在 favorites.storeid
和 favorites.person
上有索引,因为它们有 JOIN 和 WHERE 条件。