SELECT post_title,
count(*) AS c
FROM wp_posts
WHERE post_type = "product"
GROUP BY post_title
HAVING c > 1
ORDER BY c DESC
运行没问题,在不到1秒的时间内返回结果。
select * from wp_posts where post_title in (
select post_title from wp_posts WHERE post_type = "product"
group by post_title having count(*) > 1
)
挂断。
除了在第二个查询中我试图提取整个记录而不是仅post_title
之外,它们基本上是相同的查询。
我犯了错吗?有没有更有效的方法来实现这一目标?
答案 0 :(得分:1)
您可以避免在子查询上使用IN子句,而使用内部联接
select a.*
from wp_posts a
INNER JOIN (
select post_title
from wp_posts
WHERE post_type = "product"
group by post_title
having count(*) > 1
) t ON t.post_title = a.post_title
这应该表现得更好
答案 1 :(得分:0)
编写此查询的最有效方法可能是使用exists
。 。 。假设wp_posts
具有主键:
select p.*
from wp_posts p
where p.post_type = 'product' and
exists (select 1
from wp_posts p2
where p2.post_title = p.post_title and
p2.post_type = p.post_type and
p2.id <> p.id
);
为了提高性能,您希望在wp_posts(post_type, title, id)
上建立索引。