Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL how to count in a left join with where clause only for count?

Tags:

join

mysql

count

I have this two tables: ritter(ritterId, ritterName) and quest(questID, ritterID, datum).

Now my question is, how can i show all from ritter with an extra column which shows the count of quests for the ritter in the current week?

I tried this:

select r.*, count(q.ritterID) from ritter as r left join quest as q on r.ritterID = q.ritterID group by r.ritterID;

This works but without the where cause for the current week.

If i do: select r.*, count(q.ritterID) from ritter as r left join quest as q on r.ritterID = q.ritterID where weekofyear(datum) = weekofyear(now()) group by r.ritterID;

then it shows only the ritter which did a quest in the current week but i want to that it shows all the ritter.

Output:

How it is:

enter image description here

How it should be:

enter image description here

Table ritter:

enter image description here

and the table quest:

enter image description here

How can i solve this?

I hope you can understand what i mean and what i want. Sorry for my english.

like image 955
Cihat Avatar asked Sep 28 '16 09:09

Cihat


Video Answer


1 Answers

You are not far from the solution, just move the date filter from the where criteria into the join condition. This way it only applies to the table on the right hand side of the join, not the entire resultset:

select r.*, count(q.ritterID)
from ritter as r left join quest as q
   on r.ritterID = q.ritterID and weekofyear(datum) = weekofyear(now())
group by r.ritterID

Since ritter name is functionally dependent on ritter id, your query will be fine on the recent versions of MySQL. In older versions, however, you may get into trouble if only_full_group_by sql mode is set. So, it may be better to add r.ritterName to the group by clause.

like image 148
Shadow Avatar answered Sep 22 '22 20:09

Shadow