There is a hypothetical table called Table1, with the columns:
- id
- condition 1
- condition 2
- joinable_key
There is another one, Main_Table, whose ID corresponds with the joinable_key in the first one.
I would like to join them in such a fashion that I can count the rows of Table1 according to both condition 1 and condition 2 separately – that is, I would like to be able to perform “count(Table1.condition1) as first_condition, count(Table1.condtion2) as second_condition” on the select query.
The query would presumably look something like this:
SELECT Main_Table.some_column, COUNT(Table1.condition1) AS first_condition, COUNT(Table1.condtion2) AS second_condition
FROM Main_Table
LEFT JOIN Table1 AS T1 on (T1.joinable_key = Main_Table.id AND T1.condition1 = 'something')
LEFT JOIN Table1 AS T2 on (T2.joinable_key = Main_Table.id AND T2.condition2 = 'something else')
GROUP BY (Main_Table.id)
When this executes, however, both count results are equal, and actually multiply with each other.
It is imperative that all results be included in the final output – including those that do not have any entries from Table1 – that is, if there is no row in Table1 with a joinable_key equal to Main_Table.id, it too needs to be included.
Before anyone suggest actually doing two separate queries and handling it through PHP – yes, I know why and how it can be done, but my goal is to find out whether or not this multi-count can be done all in one query.
Thank you
1 Answer