1

我的评分系统有问题。

如果 中没有匹配项,LEFT JOIN则在使用时根本不会返回该行AVG()

如果连接中没有结果,则返回 NULL。

SELECT op_id,
       ...,
       rating_stars 

但这会删除该行。

SELECT op_id,
       ...,
       AVG(rating_stars) 

这是我最后一次尝试:

SELECT op_id,
       op_img,
       op_title,
       op_worktime,
       op_cookingtime,
       CASE rating_stars WHEN null THEN 0 ELSE AVG(rating_stars) END
FROM 
 opskrifter
LEFT JOIN 
  rating 
ON 
  rating.fk_op_id = opskrifter.op_id
WHERE 
  fk_type_id=1 
ORDER BY 
  op_id DESC

我需要所有结果,如果它还没有被评级,它应该像这样返回 0:

ID        | RATING
--- 1 --- | ---  0  ---
--- 2 --- | ---  4  ---
--- 3 --- | ---  0  ---

但上面的 SQL 返回:

ID        | RATING
--- 2 --- | ---  4  ---

我很确定我已经在 MySQL 中做到了这一点,没有任何问题。

4

1 回答 1

2

你需要有GROUP BY子句,

SELECT...
FROM...
WHERE...
GROUP BY op_id,
       op_img,
       op_title,
       op_worktime,
       op_cookingtime
于 2013-03-09T11:28:27.457 回答