我有这个问题:
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;
它什么都不匹配,并返回:
-+--------------------+---------------------+------------+-----------+-------+-------------+-----------+
| 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 |
+------------+-------------------+---------------+---------------------+------------+--------------------------+-----------------------+--------------------+---------------------+------------+-----------+-------+-------------+-----------+
但我想知道为什么它会返回任何东西?架构有什么问题吗?还是查询?
我正在检查它是否返回任何内容,并尝试返回404页面,但系统认为有1个返回的行,因此它会混淆我的应用程序。
我在这里可能做错了什么?
谢谢!
答案 0 :(得分:3)
尝试在查询末尾添加以下子句:
GROUP BY problems.problem_id, creator_member_id, problem_title,
problem_description, problem_date, first_name, last_name,
email, small_thumb ,mid_thumb
最佳做法是,每个选中但未聚合的列(如投票)必须在group by子句中,但MYSQL不会强制执行此操作。相反,它表现得很奇怪,让人感到困惑。 (有关更好的解释,请参阅this answer。)
答案 1 :(得分:3)
问题是由于
sum( vote ) as totalVotes
如果要将聚合函数用作SUM来对结果集进行分组,则必须使用a 声明为GROUP BY。
如果你想过滤那个结果,你应该使用HAVING
http://database-programmer.blogspot.com/2008/04/group-by-having-sum-avg-and-count.html
在你的情况下,我认为这应该有效:
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;
GROUP BY problems.problem_id , creator_member_id , problem_title , problem_description , problem_date , first_name , last_name , email , small_thumb , mid_thumb
答案 2 :(得分:-1)
首先,确保没有包含所有NULL的行
然后:LEFT JOIN关键字返回左表(table_name1)中的所有行,即使右表(table_name2)中没有匹配项也是如此。
尝试将其更改为INNER JOIN