使用单个查询更新两个表

时间:2019-10-04 10:51:31

标签: mysql

我在StackOverflow中找到了适合我需要的解决方案,但是当我使用此解决方案时,仅更新了第一个表:

这是我的查询:

UPDATE posts_flags
    INNER JOIN
    posts ON (posts_flags.content_id = posts.id )
SET 
    posts.published = 5,
    posts_flags.status = 'new_state'
WHERE posts.id = ?;

posts.published被更新,而且如果查询运行没有任何错误,则posts_flags.status不变。

怎么了?谢谢


更新

谢谢大家,真的很奇怪,现在可以正常工作了,很奇怪

1 个答案:

答案 0 :(得分:2)

查询看起来不错-这是证明

drop table if exists posts,posts_flags;

create table posts(id int,published int);
create table posts_flags(content_id int,status varchar(20));

insert into posts values(1,1);
insert into posts_flags values(1,null);

UPDATE posts_flags
    INNER JOIN
    posts ON (posts_flags.content_id = posts.id )
SET 
    posts.published = 5,
    posts_flags.status = 'new_state'
WHERE posts.id = 1;

select * 
from posts
join posts_flags on posts_flags.content_id = posts.id;

+------+-----------+------------+-----------+
| id   | published | content_id | status    |
+------+-----------+------------+-----------+
|    1 |         5 |          1 | new_state |
+------+-----------+------------+-----------+
1 row in set (0.00 sec)

如果您的模型不同,请在问题中添加表格定义和示例数据作为文本。