优化mysql查询-选择内部联接并存在

时间:2018-11-20 20:34:19

标签: mysql

我有以下mysql查询,该查询需要很长时间(4秒)才能执行。我还有其他方法可以编写它以便更快地执行。数据集很小(万行)

SELECT x.pid, x.rank, x.description, x.price, x.ifile 
FROM (SELECT product.pid, product.rank, product.description, product.price, images.ifile 
      FROM product INNER JOIN images ON product.pid=images.pid 
      WHERE EXISTS (SELECT 1 FROM links WHERE product.pid=links.pid)
) as x 
WHERE x.description LIKE '%a%' 
ORDER BY x.rank ASC 
LIMIT 0,10

我也尝试了以下类似的结果:

SELECT product.pid, product.rank, product.description, product.price, images.ifile 
FROM product INNER JOIN images ON product.pid=images.pid 
WHERE EXISTS (SELECT 1 FROM links WHERE product.pid=links.pid) 
  AND product.description LIKE '%a%' 
ORDER BY product.rank ASC 
LIMIT 0,10

2 个答案:

答案 0 :(得分:1)

相关的子查询可能相对昂贵,而不是EXISTS (SELECT 1 FROM links WHERE product.pid=links.pid)对外部查询的每一行执行一个查询,最好尝试使用product.pid IN (SELECT pid FROM links)product.pid IN (SELECT DISTINCT pid FROM links)

如果links是一个非常大表,并且product相对较小,则相关子查询仍然会更好。

答案 1 :(得分:0)

似乎您已经有了答案,但只是好奇,您可以尝试此查询吗?

select p.pid, p.rank, p.description, p.price, i.ifile 
  from product p
    inner join images i on i.pid = p.pid
    inner join links l on l.pid = p.pid
  where p.description like '%a%' 
  order by p.rank asc limit 0,10;