1. 程式人生 > >mysql複合主鍵update的問題

mysql複合主鍵update的問題

建表content_node_relation

create table content_node_relation

(
content_id varchar(20) not null,
node_id varchar(20) not null,
primary key(content_id,node_id),
content_status int(5) not null

)ENGINE=INNODB DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

content_id和node_id是複合主鍵,執行插入命令:

mysql> insert into content_node_relation(content_id,node_id,content_status) values('xiaohuangren','lab1412',1);

mysql> insert into content_node_relation(content_id,node_id,content_status) values('xiaohuangren','lab1411',1);

此時,想要更新第一行命令。

一開始輸入的語句為:

mysql> update content_node_relation set content_id = 'xiaohuangren',node_id='lab1412',content_status=3;

報錯如下:

ERROR 1062 (23000): Duplicate entry 'xiaohuangren-lab1412' for key 'PRIMARY'

換了一種語句為:

mysql> update content_node_relation set content_status=3 where content_id='xiaohuangren' , node_id='lab1412';

報錯如下:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'node
id='lab1412'' at line 1

後來找到了正確的修改方式:

mysql> update content_node_relation set content_status=3 where content_id='xiaohuangren' && node_id='lab1412';

總結:

複合主鍵更新一條記錄時,通過“&&”來實現聯合主鍵的並列關係。