在mysql中使用条件更新记录

时间:2015-03-25 06:24:26

标签: php mysql

我有以下查询

SELECT count(Distinct user_bookmarks.user_id) AS bookmark_counter, bookmark_id 
FROM user_bookmarks 
LEFT JOIN bookmarks ON user_bookmarks.bookmark_id = bookmarks.id 
group by user_bookmarks.bookmark_id

工作正常

现在我想更新书签表中的记录

UPDATE bookmark 
set bookmarks_counter = bookmark_counter from from above query 
where id = bookmark_id which is again from above query

来自上面的查询

有什么想法吗?

我们可以这样做吗?

谢谢

3 个答案:

答案 0 :(得分:2)

您可以在更新中写入查询,如此

UPDATE bookmark bk,
(   SELECT count(Distinct user_bookmarks.user_id) AS bookmark_counter, bookmark_id 
    FROM user_bookmarks 
    LEFT JOIN bookmarks ON user_bookmarks.bookmark_id = bookmarks.id 
    GROUP BY user_bookmarks.bookmark_id
) t
SET bk.bookmarks_counter = t.bookmark_counter
WHERE bk.id = t.bookmark_id

答案 1 :(得分:0)

你可以试试这个:

UPDATE dbo.bookmarks SET bookmarks_counter = result 
WHERE user_bookmarks.user_id 
IN (SELECT count(Distinct user_bookmarks.user_id)
    AS bookmark_counter, bookmark_id  FROM user_bookmarks 
    LEFT JOIN bookmarks ON user_bookmarks.bookmark_id =  bookmarks.id  
    GROUP BY user_bookmarks.bookmark_id)

答案 2 :(得分:0)

试试这个:

 UPDATE
   bookmark 
SET 
   bookmark.bookmarks_counter = other.bookmark_counter 

FROM
    (SELECT count(Distinct user_bookmarks.user_id) AS bookmark_counter, bookmark_id 
FROM user_bookmarks 
LEFT JOIN bookmarks ON user_bookmarks.bookmark_id = bookmarks.id 
group by user_bookmarks.bookmark_id) other
WHERE 
   bookmark.id = other.bookmark_id