根据IN条件应用mysql限制

时间:2019-01-23 09:11:46

标签: mysql

我有一个更新查询,该查询基于where条件更新col1并将其限制为25。是否可以将以下查询组合在一起,但限制适用于indinvidyula IN条件,而不是整个查询

UPDATE myTable SET col1 = 'ABC' WHERE col2 = 'foo' LIMIT 25
UPDATE myTable SET col1 = 'ABC' WHERE col2 = 'bar' LIMIT 25
UPDATE myTable SET col1 = 'ABC' WHERE col2 = 'abc' LIMIT 25
UPDATE myTable SET col1 = 'ABC' WHERE col2 = '123' LIMIT 25
UPDATE myTable SET col1 = 'ABC' WHERE col2 = '12a' LIMIT 25
UPDATE myTable SET col1 = 'ABC' WHERE col2 = 'bbv' LIMIT 25

示例:我知道以下内容不会达到预期的效果。但是我想针对每个条件中的每个条件实现以下查询limit

UPDATE myTable SET col1 = 'ABC' WHERE col2 IN('foo','bar','abc','123','12a','bbv') LIMIT 25

2 个答案:

答案 0 :(得分:0)

您只需按ID选择前25行,然后使用这些ID更新回数据库即可。

完全未经测试的代码:

update table set col1 = '' where id in (select id from table WHERE col2 IN('foo','bar','abc','123','12a','bbv') LIMIT 25)

答案 1 :(得分:0)

除非列表很长,否则我想将UNION用于此类事情...

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id SERIAL PRIMARY KEY
,fruit VARCHAR(12) NOT NULL
,val VARCHAR(12) NOT NULL
);

INSERT INTO my_table (fruit,val) VALUES
('orange','foo'),
('orange','foo'),
('orange','bar'),
('orange','foo'),
('orange','foo'),
('apple','bar'),
('apple','foo'),
('apple','bar'),
('apple','foo'),
('orange','foo'),
('apple','bar'),
('apple','bar');

SELECT * FROM my_table;
+----+--------+-----+
| id | fruit  | val |
+----+--------+-----+
|  1 | orange | foo |
|  2 | orange | foo |
|  3 | orange | bar |
|  4 | orange | foo |
|  5 | orange | foo |
|  6 | apple  | bar |
|  7 | apple  | foo |
|  8 | apple  | bar |
|  9 | apple  | foo |
| 10 | orange | foo |
| 11 | apple  | bar |
| 12 | apple  | bar |
+----+--------+-----+
12 rows in set (0.24 sec)

SELECT * 
  FROM 
     ( SELECT * FROM my_table WHERE fruit = 'orange' AND val = 'foo' ORDER BY id LIMIT 3 ) a
 UNION
     ( SELECT * FROM my_table WHERE fruit = 'apple' AND val = 'bar' ORDER BY id LIMIT 3 );
+----+--------+-----+
| id | fruit  | val |
+----+--------+-----+
|  1 | orange | foo |
|  2 | orange | foo |
|  4 | orange | foo |
|  6 | apple  | bar |
|  8 | apple  | bar |
| 11 | apple  | bar |
+----+--------+-----+
6 rows in set (0.09 sec)

所以...

UPDATE my_table x
  JOIN 
     ( SELECT * 
         FROM 
            ( SELECT * FROM my_table WHERE fruit = 'orange' AND val = 'foo' ORDER BY id LIMIT 3 ) a
        UNION
            ( SELECT * FROM my_table WHERE fruit = 'apple' AND val = 'bar' ORDER BY id LIMIT 3 )
     ) y
    ON y.id = x.id
   SET x.val = 'abc';

Query OK, 6 rows affected (0.01 sec)
Rows matched: 6  Changed: 6  Warnings: 0

SELECT * FROM my_table;
+----+--------+-----+
| id | fruit  | val |
+----+--------+-----+
|  1 | orange | abc |
|  2 | orange | abc |
|  3 | orange | bar |
|  4 | orange | abc |
|  5 | orange | foo |
|  6 | apple  | abc |
|  7 | apple  | foo |
|  8 | apple  | abc |
|  9 | apple  | foo |
| 10 | orange | foo |
| 11 | apple  | abc |
| 12 | apple  | bar |
+----+--------+-----+