This is the query I’m talking about:
SELECT COUNT
FROM Note N, DatePCC D
WHERE D.codClient = '2' AND
((D.CodPCC = N.CodPCC AND D.TipPCC = N.TipPCC) OR (D.CodPCC = N.CodPCCOA AND D.TipPCC = N.Relatie))
AND (N.user = 'Server' OR N.user = 'ADMIN' OR N.user = 'Simona' OR N.user =
'Viorel' OR N.user = 'Dan' OR N.user = 'Razvan') AND (N.TipNota = 'Telefon' OR N.TipNota =
'Messenger' OR N.TipNota = 'Telefon esuat' OR N.TipNota = 'Email' OR N.TipNota = 'Evaluare
curs' OR N.TipNota = 'Corespondenta' OR N.TipNota = 'Vizita') AND
(DATE(N.DataInregistrarii) >= '2000-01-01' AND DATE(N.DataInregistrarii) <= '2012-01-25')
AND 1
The problem come from the line i’ve singled out. When I use it as simply
(D.CodPCC = N.CodPCC AND D.TipPCC = N.TipPCC)
the query runs almost instantly but after I add the second part it locks up our database. I can’t, for the life of me, figure out why it impacts the duration so much since it’s simply another two comparisons among many other.
What the query does is select stuff from N X D Where either these two (CodPCC, TipPCC) from N coincide with CodPCC and TipPCC from D or (CodPCCOA, Relatie) from N coincide with the same two rows from D.
Any idea how those two simple comparisons are changing the query in such a huge way? or how I could change it to work properly?
The big difference is because you are changing a simple inner join into an expression that has to be evaluated on a cross join between the tables.
You shouldn’t write your join that way in the first place, but use the
joinkeyword:To make the new query efficient, you should make two left joins against the same table. That way the database can use index for each join instead of making a cross join.
You can also try if an
inner joinis efficient with the two sets of conditions, but it’s possible that the database can’t optimise that into a good query.