UPDATE `users` u
SET u.`user_rating`= (SELECT avg(rating)
FROM `rating` r
WHERE (r.prof_id=u.id AND r.is_prof_send=0)
OR (r.user_id=u.id AND r.is_prof_send=1))
AND u.id in(3)
您好,我需要使用第二个的平均值来更新第一个表中的评分。我添加了示例,每次均返回1作为平均值,但内部选择返回正确的值。怎么了?
答案 0 :(得分:2)
对于UPDATE
或DELETE
语句,MySql不允许在子查询(如代码)中引用目标表。
您可以使用联接。
尝试这种方式(如果这是您要应用的逻辑):
UPDATE `users` u
INNER JOIN (
SELECT u.id, avg(r.rating) avgrating
FROM `users` u INNER JOIN `rating` r
ON (r.prof_id=u.id AND r.is_prof_send=0)
OR (r.user_id=u.id AND r.is_prof_send=1)
WHERE u.id IN (3)
GROUP BY u.id
) t ON t.id = u.id
SET u.`user_rating`= t.avgrating
答案 1 :(得分:0)
SELECT返回一个表,而不是一个值。
您的查询类似于ANSI SQL语法。
tar.gz
添加与您要更新的字段returned she;
"for Mrs. Long has just been here,
and she told me all about it."
Mr. Bennet made no answer.
相同的名称avg(rating)
放在了SELECT之后,因此avg(rating) as rating
-这是布尔值and u.id in(user ids)
答案 2 :(得分:0)
我认为您的u.id in (3)
放错了位置。这是您想要的吗?
UPDATE users u
SET u.user_rating = (SELECT AVG(rating)
FROM rating r
WHERE (r.prof_id = u.id AND r.is_prof_send = 0) OR
(r.user_id = u.id AND r.is_prof_send = 1)
)
WHERE u.id IN (3);