2

我有一个名为 status_t 的表:

**id** **page** **status** **locked**_by
  1      0        2          0
  1      1        2          0
  1      2        2          0
  2      0        0          0
  2      1        2          0
  2      2        2          0

主键是 (id, page) 。

在上面的示例中,我想更新所有页面状态 = 2 的所有行。

查询应该将所有 id = 1 的行更新为状态 3。所以表将变为

**id** **page** **status** **locked**_by
  1      0        3          1
  1      1        3          1
  1      2        3          1
  2      0        0          0
  2      1        2          0
  2      2        2          0

我试过了:

SELECT * FROM  status_t AS t
 WHERE id IN   
 (SELECT id FROM status WHERE status = 0) LIMIT 10

上面的查询获取要更新的行,但我不能这样做:

UPDATE status_t as S1 WHERE id IN 
(SELECT id FROM status_t WHERE status = 2) 
SET S1.status = 3, S1.locked_by = 1

编辑:

上表只是一个例子。

我不想更新 WHERE id = 1 。我只想更新行,无论具有相同 ID 的状态 = 2 的 ID。在上面的示例中,如果键为 (2, 2) 的行的状态 = 2,那么它应该被更新。

4

6 回答 6

1

试试这个:

UPDATE status_t a 
INNER JOIN (SELECT id FROM status_t WHERE STATUS = 2 GROUP BY id HAVING COUNT(*) = 3 LIMIT 1) AS b ON a.id = b.id
SET a.status = 3, a.locked_by = 1;

这将根据需要更新所有页面的数据,状态 = 2

于 2012-11-29T11:02:25.183 回答
1

这应该有效:

update status_t t
join (
    select distinct id from status_t s
    where status=2 and not exists (
        select 1 from status_t ss
        where s.id=ss.id and s.status <> ss.status
    )
) i on i.id = t.id
set t.status = 3

内部查询选择所有值status都设置为的 ID 2。它通过检查没有具有相同 ID 和不同状态的行来实现此结果。

这是关于 sqlfiddle 的演示

于 2012-11-29T11:05:02.513 回答
0

以下应该可以解决问题:

UPDATE status_t 
SET status = 3, locked_by = 1 
WHERE status = 2

应该不需要使用子查询,因为 WHERE 应该能够直接在 UPDATE 语句中使用。

编辑:

我刚刚注意到您只对带有 的行进行了更新ID = 1,这与“在上面的示例中我想更新所有页面的状态 = 2 的所有行。id . The rows where= 2状态 = 2”的语句不匹配, and由我的查询更新。

如果您只需要更新特定的 id,请在我的查询末尾添加以下内容:

AND id = 1

于 2012-11-29T10:49:33.390 回答
0

试试这个::

UPDATE status_t SET status = 3, locked_by = 1 WHERE status = 2

如果您想以自己的方式实现这一目标:

UPDATE 
status_t as S1 
INNER JOIN 
(
   SELECT keyword_id 
    FROM status_t WHERE status = 2
 ) as tempStatus ON id= tempStatus.keyword_id

SET S1.status = 3, S1.locked_by = 1
于 2012-11-29T10:50:28.830 回答
0

试试这个

  update status_t set staus=3 ,locked_by=1 
  where id=1

或者

 update status_t set status=3 ,locked_by=1 
  where status=2
于 2012-11-29T10:50:56.090 回答
0
UPDATE status_t SET status = 3, S1.locked_by = 1 WHERE id = 1
于 2012-11-29T10:52:56.057 回答