mysql updata 两个表 sql语句怎么写
表1
id title cid pid
1 a 11 空
2 b 12 空
3 c 11 空
4 d 12 空
5 e 11 空
表2
id pid
11 5
12 6
表1的cid就是表2的id,现在要根据表1的cid的值,通过表2的id与pid对应关系,来更新表1的pid值。
sql语句应该怎么写?
最终结果
表1
id title cid pid
1 a 11 5
2 b 12 6
3 c 11 5
4 d 12 6
5 e 11 5
[SQL]update t1,t2 set t1.pid = t2.pid where t1.cid= t2.id
受影响的行: 0
时间: 0.002s
[Err] 1055 - Expression #1 of ORDER BY clause is not in GROUP BY clause and contains nonaggregated column 'information_schema.PROFILING.SEQ' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
BEGIN
declare c_id int;
declare p_id int;
declare done int default FALSE;
declare v_cur CURSOR for select t2.id as c_id, t2.pid as p_id from t1,t2 where t1.cid = t2.id;
declare continue HANDLER for not found set done = TRUE;
open v_cur;
read_loop:LOOP
fetch v_cur into c_id,p_id;
update t1 set pid = p_id where cid = c_id;
IF done THEN
LEAVE read_loop;
END IF;
END LOOP read_loop;
COMMIT;
CLOSE v_cur;
END;
update 表1 a, 表2 b set a.pid= b.pid where a.cid=b.id
表结构如下:
执行的sql语句如下:
UPDATE table1 t1 SET pid=(select t2.pid FROM table2 t2 WHERE t2.id=t1.cid)
执行结果如下:
我用的是mysql的数据库,如果执行时提示你如下错误,是因为你的数据库在【safe-update】的模式下,非主键条件下无法执行update或delete语句
Error Code: 1175. You are using safe update mode and you tried to update a table without a WHERE that uses a KEY column To disable safe mode, toggle the option in Preferences -> SQL Editor and reconnect.
解决方法,先修改数据库的更新模式,语句如下:
SET SQL_SAFE_UPDATES=0;
再执行上述的update语句就好了,如果你想将数据库的更新模式修改回来,请执行如下语句:
SET SQL_SAFE_UPDATES=1;
如果我的回答对您有所帮助,请您采纳,谢谢~~