选择内部连接并存在

e4eetjau  于 2021-06-19  发布在  Mysql
关注(0)|答案(2)|浏览(416)

我有下面的mysql查询,查询需要很长时间(4秒)才能执行。有没有其他方法可以让我写出来,这样执行起来会更快。数据集相当小(10000行)

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
1l5u6lss

1l5u6lss1#

相关子查询可能相对昂贵,而不是 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 有一张很大的table product 相对较小,相关子查询可能更好。

moiiocjp

moiiocjp2#

你似乎已经有了答案,但只是好奇,你能试试这个问题吗?

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;

相关问题