0
I’m trying to optimize a Query that the system I’m working on makes it have a SubQuery inside, only this SubQuery is referencing another table that has relation to the main table and by what I’ve been researching maybe if the Query used the Join instead of a SubQuery would be faster, the Query is this:
SELECT COUNT(v.id_voto) FROM radar.rad_voto AS v
WHERE (
SELECT COUNT(vi.id_votoitem) FROM radar.rad_votoitem AS vi
WHERE (
vi.id_alternativa IN (1068, 1061)
) AND vi.id_voto = v.id_voto
) = 2;
My attempt to convert to Join glitch:
SELECT count(*) FROM radar.rad_voto AS v
JOIN radar.rad_votoitem AS vi ON vi.id_voto = v.id_voto
WHERE (
(vi.id_alternativa IN (1068, 1061)) AND vi.id_voto = v.id_voto
);
The schematic of the two tables is this:

Someone could give me a light?
(Note: I don’t have much experience in SQL, I know the basics to survive)
Edit 1: What I want to do is count the number of times that on the table rad_votoitem has two lines with two id_alternativa different (with value I will specify, those there are merely to exemplify) and these two lines have the same id_voto
Not much time to explore, but I think you can use the clase
HAVINGSQL to make this filter.– Jefferson Quesado
Explain better what you want to tell. At least this: AND vi.id_voto = v.id_voto you don’t need because you are already in the joining condition.
– anonimo
@anonimo I am wanting to count the number of times that in the table
rad_votoitemhas two lines with twoid_alternativadifferent (with value that I will quote, I used those there merely to exemplify) and these two lines have the sameid_voto– Bruno
@Jeffersonquesado how could I use to get my desired result? Can you illustrate?
– Bruno
But you need some more data from the rad_vote table or the count/selection is all done in the rad_votoitem table?
– anonimo
@anonimo I don’t know if I understand your question but what I want is just count how many times q in the table
rad_votoitemhas two lines withid_alternativadistinct andid_votoequal– Bruno