I am trying to fetch data from a SQL DB via PHPmyAdmin but it takes ages to excute my query. Do you have any idea how to speed up my query ?
My DB has the following structure
Table joueurs
| id_joueur | mail |
Table paires
| paires.annee | idj1 | idj2 |
Thanks alot
/* mail from all players being first memeber of a pair (idj1)
in 2015, 2016 and 2017 and removing doubles*/
SELECT
mail
from
joueurs
where
(joueurs.id_joueur in
(SELECT idj1
FROM paires
WHERE (paires.annee = 2015 OR paires.annee = 2016 OR paires.annee = 2017)
)
)
GROUP BY mail
HAVING COUNT(*) > 0
I would remove the subquery and just join
the two tables. And also where
clause might be better with a condition like paires.annee > 2014 and paires.annee < 2018
. But the only way to improve it is to add indices to the tables.
SELECT
j.mail
FROM
joueurs j
JOIN paires p on p.idj1 = j.id_joueur
WHERE p.annee > 2014 and p.annee < 2018
GROUP BY j.mail
HAVING COUNT(*) > 0
You can use Exists
on place of in, something like this
SELECT
j.mail
from
joueurs j
where
Exists
(SELECT idj1
FROM paires
WHERE idj1 =j.id_joueur and (paires.annee = 2015 OR paires.annee = 2016 OR paires.annee = 2017 )
)
GROUP BY j.mail
HAVING COUNT(*) > 0
EDIT : SQL Server IN vs. EXISTS Performance here you can read about Exists
and IN
My initial recommendation is:
select distinct j.mail
from joueurs j
where exists (select 1
from paires p
where p.idj1 = j.id_joueur and p.annee in (2015, 2016, 2017)
);
The having
clause does nothing. For performance, you want an index on paires(idj1, annee)
.
If this still takes a long time, what happens if you remove the distinct
? Are the results still acceptable?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.