I have this query and result in my database:
mysql> SELECT id FROM jos_content
WHERE catid=12 AND state=1
AND DATE(publish_up) <= NOW() ORDER BY DATE(publish_up) DESC LIMIT 0,5;
+----+
| id |
+----+
| 48 |
| 47 |
| 46 |
+----+
3 rows in set (0.00 sec)
Now I would like to count result:
mysql> SELECT count(*), id FROM jos_content
WHERE catid=12 AND state=1
AND DATE(publish_up) <= NOW() ORDER BY DATE(publish_up) DESC LIMIT 0,5;
+----------+----+
| count(*) | id |
+----------+----+
| 3 | 46 |
+----------+----+
1 row in set (0.00 sec)
Why aren’t the 48 and 47 results shown?
Thank you in advance
You need to include a
GROUP BYclause. By default, MySQL permits columns in theSELECTclause which are not also included in aGROUP BY(which is an error in most other RDBMS). Without theGROUP BY, MySQL will return the first of the associated columns, which is often not the correct intended result.Not requiring all columns in the
GROUP BYis helpful if you want to return multiple columns in a summary which are always unique, as something like the following, wherenameis unique toid, but you MUST group at least one column for an aggregate to act correctly and produce a summary:For compatibility with other RDBMS, and to avoid bugs, I recommend always including all the
SELECTcolumns in theGROUP BYexplicitly.Update
With better understanding of what you attempted, if you want the total count of all rows beside the id of each row, you can use a subselect like in the
SELECTlist. This is going to be a bit slow though.You can trick this to work a little faster by doing a cartesian join (no
ONclause) against the count in a subquery, so it shouldn’t get executed for each row. Only do this if the subquery will return exactly one row.