左连接在UPDATE上过滤行?

时间:2012-09-25 04:14:07

标签: mysql sql

我正在尝试更新表,但我需要执行左连接以确定要选择哪些行。

这是我一直在尝试的两个例子,我认为通过查看其中任何一个我很清楚我想做什么:

   UPDATE `User_Likes` 
      SET `Status` = 'read'
LEFT JOIN Posts ON User_Likes.PID = Posts.ID
    WHERE Posts.UID = '1'

我在尝试另一种方式:

UPDATE `User_Likes` 
   SET `Status` = 'read' 
 WHERE `ID` IN (SELECT Posts.ID
                  FROM `User_Likes`
             LEFT JOIN Posts ON User_Likes.PID = Posts.ID
                 WHERE Posts.UID = '$userID')

3 个答案:

答案 0 :(得分:0)

看一下这个例子

UPDATE User_Likes
LEFT JOIN
Posts ON User_Likes.PID = Posts.ID 
SET Status='read'
WHERE Posts.UID = '1' ;

SQL Fiddle DEMO

答案 1 :(得分:0)

您的查询的问题是Id只需要一个Id,而您的select语句会返回多个ID。 这样:

UPDATE `User_Likes` 
   SET `Status` = 'read'
FROM `User_Likes`
LEFT JOIN Posts ON User_Likes.PID = Posts.ID
WHERE Posts.UID = '$userID'

有点像这样......

答案 2 :(得分:0)

UPDATE `User_Likes` u LEFT JOIN Posts p 
ON u.User_Likes.PID = p.Posts.ID
SET `Status` = 'read'
WHERE p.Posts.UID = '1'