如何分配变量以选择和更新字段

时间:2017-03-29 13:12:55

标签: mysql

我的表中有两列,我正在尝试使用第一列的结果更新第二列。

SET @pg = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'x' LIMIT 1)

现在上面的查询工作了(SELECT ...),因为它从查询返回一个ID,所以我试图使用该ID来更新这样的另一列。

UPDATE wp_posts SET post_type = 'foo' WHERE ID = @pg; 

但出于某种原因上述情况不起作用。

我收到以下错误。

1 queries executed, 0 success, 1 errors, 0 warnings

Query: set @pg = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'x' LIMIT 1) SELECT * ...

Error Code: 1064
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'SELECT * FROM wp_posts WHERE id = @pg' at line 3

Execution Time : 0 sec
Transfer Time  : 0 sec
Total Time     : 0 sec

EDIT / UPDATE:

我也在尝试执行这个staetment,这更简单并且做同样的事情

UPDATE wp_posts SET post_type = 'x' WHERE ID = (SELECT ID FROM wp_posts WHERE post_name = 'y' AND post_status = 'z' LIMIT 1)

但由于某种原因,它不起作用。

1 个答案:

答案 0 :(得分:1)

您可以尝试使用JOIN更新

UPDATE wp_posts AS a 
       INNER JOIN wp_posts AS b ON a.id = b.id 
SET    a.post_type = 'x' 
WHERE  b.post_name = 'y' 
       AND b.post_status = 'z'   

或者将更新条件包装在另一个选择

UPDATE wp_posts 
SET    post_type = 'x' 
WHERE  id IN (SELECT id
              FROM   (SELECT id 
                      FROM   wp_posts 
                      WHERE  post_name = 'y' 
                             AND post_status = 'z') AS SOURCE)