You can't specify target table '表名' for update……

建表sqlsql

DROP TABLE IF EXISTS `car`;
CREATE TABLE `car` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `type_id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  `num` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of car
-- ----------------------------
INSERT INTO `car` VALUES ('1', '1', '張三', '3');
INSERT INTO `car` VALUES ('2', '2', '李四', '2');
INSERT INTO `car` VALUES ('3', '3', '王五', '4');
INSERT INTO `car` VALUES ('4', '4', '趙六', '1');
INSERT INTO `car` VALUES ('5', '1', '李四', '2');

-- ----------------------------
-- Table structure for `car_type`
-- ----------------------------
DROP TABLE IF EXISTS `car_type`;
CREATE TABLE `car_type` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `money` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of car_type
-- ----------------------------
INSERT INTO `car_type` VALUES ('1', '奧迪', '300');
INSERT INTO `car_type` VALUES ('2', '奔馳', '500');
INSERT INTO `car_type` VALUES ('3', '寶馬', '350');
INSERT INTO `car_type` VALUES ('4', '大衆', '200');

一條sql語句更新,將money大於200的num數量若是等於3則加3,若是等於2則加1,若是等於1則加2.code

update car set num =
	case when num = 3 then  num+3
	when num = 2 then num+1
	when num = 1 then num+2 	
	else num
 	end
where  id in (
select t.id
from 
(  select c.id id from car c left join car_type t on c.type_id = t.id where money > 200 ) t )

報錯[Err] 1093 - You can't specify target table 'car' for update in FROM clauseblog

相關文章
相關標籤/搜索