Keep in mind how JOIN
and GROUP BY
work together. First the JOINs
are done. This explodes into a big temp table. Second the GROUP BY
shrinks id down to essentially what you started with. Let's avoid that "inflate-deflate":
select k1.sto, k1.mm,k1.dd, k1.yy, k1.sto_name, k1.trannum,
( SELECT count(k2.barcode) FROM trans012020 as k2
WHERE k1.mm=k2.mm
and k1.dd=k2.dd
and k1.yy=k2.yy
and k1.sto=k2.sto
and k1.trannum=k2.trannum
) as k2count
from trans012020 as k1
where k1.barcode=123456789
having k2count=1;
If barcode
is NOT NULL
, change count(k2.barcode)
to simply COUNT(*)
.
k1 needs an INDEX
(or the PRIMARY KEY)
beginning with barcode
.
If k2count can never be more than 1, then there is an even better way:
select k1.sto, k1.mm,k1.dd, k1.yy, k1.sto_name, k1.trannum
from trans012020 as k1
where k1.barcode=123456789
AND EXISTS ( SELECT 1 FROM FROM trans012020 as k2
WHERE k1.mm=k2.mm
and k1.dd=k2.dd
and k1.yy=k2.yy
and k1.sto=k2.sto
and k1.trannum=k2.trannum )
And, yes, this is desirable for k2
:
INDEX(mm, dd, yy, sto, trannum)
(The order of the columns is not important for this query.)
Note that the GROUP BY
went away.