0

I have the following SQL query that performs horribly due to the select count(1) statement in the where clause. Can anyone suggest a way that would speed this up? The idea is that I only want rows returned where there is one invoice found.

SELECT people.name, people.address 
FROM people 
WHERE ((SELECT COUNT(1) FROM invoices WHERE invoices.pid = people.id)=1)

3 Answers 3

4

So, try a JOIN like this

SELECT people.name, people.address 
FROM
   people 
   JOIN
   invoices ON invoices.pid = people.id
GROUP BY
   people.name, people.address 
HAVING
   COUNT(*) = 1

I'd also hope you have indexes, at least on invoices.pid and people.pid, name, address

Sign up to request clarification or add additional context in comments.

2 Comments

Learn something new everyday. Never heard the voodoo of Count(1). I wonder if that was created by some SEO guy...
Thanks! Really Box 9 had the answer below too but your explanation of the "superstition" and the additional info helped.
1

Use a JOIN:

SELECT people.name, people.address
FROM people
JOIN invoices ON invoices.pid = people.id
GROUP BY people.name, people.address
HAVING Count(*) = 1

Comments

0

Joining the tables is probably going to be much better in practice and in performance, I should think.

SELECT people.name, people.address 
FROM people INNER JOIN invoices ON invoices.pid = people.id

Edit due to OP being edited: do you want only those people who have exactly one invoice? If so then disregard this and look at one of the other answers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.