0

I have the following tables:

list

  • id - key
  • name

item

  • id - key
  • name

list_item

  • list_id - foreign key to list table
  • item_id - foreign key to item table

I have the following query:

SELECT l.id, l.name
FROM list l, list_item li
WHERE l.id = li.list_id

I want to add to the result set, the count of items in the list. How do I do this?

1
  • have you tried adding COUNT() to your query? Also please add some sample data and the expected result. Commented Oct 4, 2012 at 2:27

2 Answers 2

4
SELECT l.id, l.name, COUNT(li.item_id) AS item_count 
FROM list l
LEFT JOIN list_item ON l.id = li.list_id
GROUP BY l.id
Sign up to request clarification or add additional context in comments.

4 Comments

Shouldn't l.name be part of the GROUP BY clause?
l.id is the key of the list, why should l.name be part of the GROUP BY clause?
Seems to be valid in MySQL (but SQL Server complains that all columns other than those on which aggregate functions are applied, must be in the GROUP BY list). Sorry for false alarm!
@Vikdor Yes, you are right, this is MySQL special thing. Your alarm make sense if this is not MySQL :)
1

Try this:

SUM(l.id = li.list_id)

2 Comments

Did you mean to say COUNT instead of SUM?
I think SUM will work just fine here, COUNT should work as well but SUM is much more flexible...

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.