0

I have these two tables (Article and Sale):

id  |  name     |
====+============
1   |   milk    |
2   |   apple   |
3   |   bread   |
... |    ...    |


id  |   idArticle  |   date     |
====+==============+=============
1   |       2      | 2011-01-01 |
2   |       2      | 2011-01-01 |
3   |       3      | 2011-01-01 |
4   |       1      | 2011-01-02 |
... |      ...     |    ...     |

I need to get the sales for 2011/01/01: article and count

2011-01-01 Milk 0
2011-01-01 Apple 2
2011-01-01 Bread 1
...

But I don't know how to show "Milk: 0" because it didn't sell milk that day.

This query doesn't work:

SELECT s.date, a.name, COUNT(*)
FROM article a
LEFT JOIN sale s ON a.id = s.idArticle
WHERE s.date = "2011-01-01"
GROUP BY s.date, a.name
4
  • read this. dev.mysql.com/doc/refman/5.0/en/join.html Left join is your mistake here. Try inner join Commented Jun 5, 2012 at 9:13
  • @Bondye: but he wants it that way, look at the desired output (milk)... Commented Jun 5, 2012 at 9:31
  • @pOcHa But I don't know how to show "Milk: 0" because it didn't sell milk that day. Have you realy read this question? Commented Jun 5, 2012 at 10:08
  • @Bondye: my answer already takes care of all that, it displays the output exactly as desired, and is optimized for speed too (grouping before joining) - his query shows milk (as intended) but no date and displays 1 instead of 0 (and with inner join there would not be milk at all, do you get it now?) Commented Jun 5, 2012 at 10:14

2 Answers 2

2
SELECT "2011-01-01" AS date, a.name, IFNULL(s.total, 0)
FROM article a
LEFT JOIN (
    SELECT idArticle, COUNT(*) AS total
    FROM sale
    WHERE date = "2011-01-01"
    GROUP BY idArticle
) AS s ON a.id = s.idArticle
Sign up to request clarification or add additional context in comments.

1 Comment

just change "2011-01-01" to a @date parameter, and it will work for any day - and if you want it for a date range, then change WHERE date = "2011-01-01" to WHERE date BETWEEN @dateMin AND @dateMax, but remove date column from select...
0
SELECT a.name, COUNT(s.id)
FROM article a
LEFT JOIN sale s ON a.id = s.idArticle AND s.date = '2011-01-01'
GROUP BY a.name

1 Comment

what exactly are you counting without the GROUP BY a.name

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.