mysql 批量更新多字段

一般情况下,mysql更新语句为:update tableName set 字段=值;并没有提供直接批量更新的方法,但是我们可以使用case   when 来代替,语句如下:

                             

UPDATE PUBLIC_KEY_BASIC_SERVICE 
SET POLICED =
CASE
		ID 
		WHEN 36 THEN
		'1' 
		WHEN 42 THEN
		'1' 
		WHEN 43 THEN
		'1' 
		WHEN 44 THEN
		'1' 
		WHEN 45 THEN
		'1' 
		WHEN 47 THEN
		'1' 
		WHEN 47 THEN
		'1' 
		WHEN 48 THEN
		'1' 
		WHEN 49 THEN
		'1' 
	END
	WHERE
		ID IN (
			36,
			42,
			43,
			44,
			45,
			46,
			47,
		48,
	49)

上面语句是批量更新多行数据和一个字段的值,当然,如果需要批量更新多行数据多个字段的话也是可以的,语句如下:

UPDATE PUBLIC_KEY_BASIC_SERVICE 
SET POLICED =
CASE
		ID 
		WHEN 1 THEN
		'1' 
		WHEN 2 THEN
		'1' 
		WHEN 15 THEN
		'1' 
		WHEN 16 THEN
		'1' 
		WHEN 17 THEN
		'1' 
		WHEN 20 THEN
		'1' 
		WHEN 21 THEN
		'1' 
		WHEN 22 THEN
		'1' 
		WHEN 23 THEN
		'1' 
	END,
	REORDER =
CASE
		ID 
		WHEN 1 THEN
		'1' 
		WHEN 2 THEN
		'2' 
		WHEN 15 THEN
		'3' 
		WHEN 16 THEN
		'4' 
		WHEN 17 THEN
		'5' 
		WHEN 20 THEN
		'6' 
		WHEN 21 THEN
		'7' 
		WHEN 22 THEN
		'8' 
		WHEN 23 THEN
		'9' 
	END,
	NOMAlPEOPLE =
CASE
		ID 
		WHEN 1 THEN
		'0' 
		WHEN 2 THEN
		'0' 
		WHEN 15 THEN
		'0' 
		WHEN 16 THEN
		'1' 
		WHEN 17 THEN
		'0' 
		WHEN 20 THEN
		'0' 
		WHEN 21 THEN
		'0' 
		WHEN 22 THEN
		'0' 
		WHEN 23 THEN
		'0' 
	END
	
WHERE
	ID IN (
		1,
		2,
		15,
		16,
		17,
		20,
		21,
	22,
	23)

注意,俩个字段之间用逗号分隔,最后一个无需逗号!!!

你可能感兴趣的:(mysql专栏)