在UPDATE语句中计算LEFT JOIN中的值

时间:2014-07-04 10:24:59

标签: mysql

我试图将多个MySQL语句合并为一个。以下是我提出的建议:

UPDATE users 
LEFT JOIN (SELECT COUNT(*) FROM activity_profileviews WHERE puid = 2 AND date > 100000) AS total_profileviews
LEFT JOIN (SELECT COUNT(DISTINCT from_id) AS total_messages FROM messages WHERE to_id = 2 AND time_sent > 100000) AS total_messages
LEFT JOIN (SELECT COUNT(DISTINCT uid) AS total_favorites FROM favorites WHERE favorite_uid = 2 AND date > 100000) AS total_favorites 
SET users.popularity = (total_profileviews + (total_messages * 10) + (total_favorites * 5)) 
WHERE id = 2 

MySQL给了我错误:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET users.popularity = (total_profileviews + (total_messages * 10) + (total_favo' at line 5 

我做错了什么?

修改

好的,花了一段时间,但这就是我想出来的。这是实现这一目标的最佳方式吗?似乎它可以更好地优化。

UPDATE
    users 
SET
    users.popularity = (
        SELECT
            (total_profileviews + (total_messages * 10) + (total_favorites * 5)) AS new_popularity
        FROM
            (SELECT COUNT(*) AS total_profileviews FROM activity_profileviews WHERE puid = 2 AND date > 100000) t1,
            (SELECT COUNT(DISTINCT from_id) AS total_messages FROM messages WHERE to_id = 2 AND time_sent > 100000) t2,
            (SELECT COUNT(DISTINCT uid) AS total_favorites FROM favorites WHERE favorite_uid = 2 AND date > 100000) t3
    )
WHERE
    users.id = 2

0 个答案:

没有答案