查询avoding subselect

时间:2011-09-23 14:00:30

标签: mysql optimization subquery

我有这个查询,但速度很慢。我可以通过避免子选择以其他方式编写此查询吗?

我也尝试在

上添加复合索引
MyIndex(kategorije_id,izdvojen,izdvojen_kad,datum)

但是当我解释这个查询时它会使用它,那么是否有另一个索引可以用来加速这个查询?

SELECT artikli.datum AS brojx, artikli.izdvojen AS i, artikli.izdvojen_kad AS ii, artikli.name
FROM artikli
WHERE artikli.izbrisan =0
AND artikli.prodano !=3
AND artikli.zavrseno =0
AND artikli.od_id !=0
AND kategorije_id
IN ( 18 )
AND (
SELECT count( * )
FROM artikli_polja, polja
WHERE polja.id_kat = artikli.kategorije_id
AND artikli_polja.id_polja = polja.id
AND artikli_polja.id_artikal = artikli.id
AND polja.name = "godiste"
AND artikli_polja.valueInt >= "1993"
) >0
AND (
SELECT count( * )
FROM artikli_polja, polja
WHERE polja.id_kat = artikli.kategorije_id
AND artikli_polja.id_polja = polja.id
AND artikli_polja.id_artikal = artikli.id
AND polja.name = "godiste"
AND artikli_polja.valueInt <= "2000"
) >0
ORDER BY i DESC , ii DESC , brojx DESC
LIMIT 140 , 35

2 个答案:

答案 0 :(得分:1)

尝试此查询 -

SELECT a.datum AS brojx, a.izdvojen AS i, a.izdvojen_kad AS ii, a.name FROM artikli a
  JOIN artikli_polja ap
    ON ap.id_artikal = a.id
  JOIN polja p
    ON ap.id_polja = p.id AND p.id_kat = a.kategorije_id
WHERE
  a.izbrisan =0
  AND a.prodano !=3
  AND a.zavrseno =0
  AND a.od_id !=0
  AND kategorije_id = 18
  AND p.name = 'godiste'
  AND ap.valueInt >= 1993 AND ap.valueInt <= 2000;

我已从查询中删除了ORDER BY和LIMIT子句;首先尝试解决这个问题。

答案 1 :(得分:1)

尝试此查询:

SELECT a.datum AS brojx, a.izdvojen AS i, a.izdvojen_kad AS ii, a.name 
FROM artikli a
WHERE a.izbrisan =0
AND a.prodano !=3
AND a.zavrseno =0
AND a.od_id !=0
AND a.kategorije_id = 18
AND EXISTS 
   (select 'X' 
   from artikli_polja ap,
   JOIN polja p
   ON ap.id_polja = p.id AND p.id_kat = a.kategorije_id
   AND ap.id_artikal = a.id
   AND p.name = 'godiste'
   AND ap.valueInt >= 1993 AND ap.valueInt <= 2000
   );

请检查。