使用下表:
post_meta
-----
meta_id post_id key value
-----
22 4546 Advantages old value
23 4546 Article number 123
帖子
-----
id status
-----
4546 pending
4547 publish
4548 publish
我正在尝试编写更新查询以将“旧值”更改为“新值”,对于设置为“待处理”的帖子,其 ID 对应于“文章编号”设置为“123”的 post_meta 的 post_id。
我不知道如何进行……有什么想法吗?
最佳答案
如果您打算更改带有 meta_key = 'Advantages'
的行的值来自 'old value'
至 'new value'
对于带有 meta_key = 'Article'
的行和 value = '123'
存在对应的 post_id
在posts
与 status = 'Pending'
那么我想你想要的查询是这样的:
update post_meta
join (
select pm.meta_id
from post_meta pm
join posts p on pm.post_id = p.id
where p.status = 'pending'
and pm.`key` = 'Advantages' -- or pm.value = 'old value'
and exists (
select 1
from post_meta
where post_id = pm.post_id
and `key` = 'Article number' and value = '123')
) t on post_meta.meta_id = t.meta_id
set value = 'new value';
对于您的示例数据,这将留下 post_meta
表格看起来像这样:
| meta_id | post_id | key | value |
|---------|---------|----------------|-----------|
| 22 | 4546 | Advantages | new value |
| 23 | 4546 | Article number | 123 |
关于使用两个表的 MySQL UPDATE 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32649934/