MySQL UPDATE查询使用两个表

时间:2015-09-18 10:37:24

标签: mysql sql

使用下表:

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

我正在尝试编写一个UPDATE查询来更改旧值'对于已设置和待定的帖子,以及“#39;新值'哪个id对应于post_meta的post_id,其中包含'商品编号'设置为' 123'。

我不知道如何继续...任何想法?

2 个答案:

答案 0 :(得分:1)

如果您的目的是将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';

Sample SQL Fiddle

使用您的示例数据,这将使post_meta表看起来像这样:

| meta_id | post_id |            key |     value |
|---------|---------|----------------|-----------|
|      22 |    4546 |     Advantages | new value |
|      23 |    4546 | Article number |       123 |

答案 1 :(得分:-1)

更新了查询

UPDATE post_meta pm, (
    SELECT pm2.meta_id 
    FROM posts p 
    INNER JOIN post_meta pm1 ON p.id=pm1.post_id
    INNER JOIN post_meta pm2 ON p.id=pm2.post_id
WHERE
    pm1.key='Article Number' AND pm1.value = 123
    AND pm2.key='Advantages' AND pm2.value = 'old value'
    AND p.status = 'pending'
) p
SET pm.value = 'new value'
WHERE pm.meta_id=p.meta_id