I have this query:
select problems.problem_id , creator_member_id , problem_title , problem_description , sum( vote ) as totalVotes , DAYOFMONTH(problem_date) , DAYNAME(problem_date) , YEAR(problem_date) , MONTH(problem_date) , first_name , last_name , email , small_thumb , mid_thumb
from problems
left join problem_votes
on problems.problem_id = problem_votes.problem_id
left join users
on problems.creator_member_id = users.user_id
left join member_photo
on problems.creator_member_id = member_photo.member_id
where problems.problem_id = 1;
It matches nothing, and returns this:
-+--------------------+---------------------+------------+-----------+-------+-------------+-----------+
| problem_id | creator_member_id | problem_title | problem_description | totalVotes | DAYOFMONTH(problem_date) | DAYNAME(problem_date) | YEAR(problem_date) | MONTH(problem_date) | first_name | last_name | email | small_thumb | mid_thumb |
+------------+-------------------+---------------+---------------------+------------+--------------------------+-----------------------+--------------------+---------------------+------------+-----------+-------+-------------+-----------+
| NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
+------------+-------------------+---------------+---------------------+------------+--------------------------+-----------------------+--------------------+---------------------+------------+-----------+-------+-------------+-----------+
But I wonder why it returns anything at all? Is there something wrong with the schema? Or the query?
I am checking whether it returns nothing, and trying to return 404 page, but the system thinks there is 1 returned row, so it confuses my application.
Anything I might be doing wrong here?
Thanks!!
Try adding the following clause to the end of your query:
Best practice is that every column that is selected but not aggregated (like vote) must be in the group by clause, though MYSQL does not enforce this. Instead, it behaves strangely and confuses people. (See this answer for a better explanation.)