更新选定的行

时间:2019-02-13 06:08:43

标签: mysql sql

我有一个如下表

    name    spent
    a       3.2
    a       5.5
    a       3
    b       4.6
    b       16
    c       1.2
    c       7

我想更新名称为“ a”的前2个用完的列

我想在一个查询中完成

我想要的结果

    name    spent
    a       1
    a       1
    a       3
    b       4.6
    b       16
    c       1.2
    c       7

6 个答案:

答案 0 :(得分:3)

您可以使用limit仅更新name = a的前两行:

update TABLE
set spent = 1
where name = a
order by id
limit 2;

答案 1 :(得分:1)

为什么你不只是考虑id

update table
  set spent=1
where id in (1,4) and name='a'

更新问题时,示例数据中没有ID,因此您可以使用子查询

UPDATE table1
SET spent = 1
WHERE spent IN (SELECT spent 
             FROM table1
             WHERE name = 'a'
             ORDER BY spent
             LIMIT 2) and name='a';

select * from table1 order by name,spent;
name    spent
  a     1
  a     1
  a     3
  b     4.6
  b     16
  c     1.2
  c     7

答案 2 :(得分:1)

update table_name set spent='1' where name='a' and id in (4,1)

答案 3 :(得分:1)

您需要使用子查询来查找名称为id的值的前2行的a个值,然后仅UPDATE个具有这些id的行值:

UPDATE table1
SET spent = 1
WHERE id IN (SELECT id 
             FROM table1
             WHERE name = 'a'
             ORDER BY id
             LIMIT 2);
SELECT * FROM table1

输出:

id  name    spent
6   a       3
1   a       1
4   a       1
2   b       16
5   b       4.6
7   c       1.2
3   c       7

Demo on dbfiddle

答案 4 :(得分:0)

update tablename set spent = 1 where name = 'a' and id in (select top 2 id from tablename where name = 'a' order by id asc)

我会先选择一个顶部,然后根据该选择生成的ID从那里更新

答案 5 :(得分:-1)

update table_name set spent=1 where name='a' and spent>3