MySQLã® LAST_INSERT_ID ã®æåã«ã¤ãã¦å°ã調ã¹ã¦ã¿ã
ä¸æãªIDãåå¾ããããã®æ¡çªãã¼ãã«ãå©ç¨ãããã£ãã®ã ãã
ãã¹ããã©ã¯ãã£ã¹ã¨ãã¦è²ããªãµã¤ãã«æ¸ããã¦ããããæ¹ã以ä¸ã
update num set id = LAST_INSERT_ID(id + 1); select LAST_INSERT_ID();
ã ããããã£ã¦ããã¨ã¯ç解ã§ããï¼æ¡çªãã¼ãã«ãæ´æ°ãã¦ãæ´æ°å¾ã®ãã¼ã¿ãselectï¼
ã®ã ãã
LAST_INSERT_ID ã£ã¦ãªããããï¼ã¨ãªã£ãã®ã§èª¿ã¹ã¦ã¿ãã
LAST_INSERT_IDを使って採番テーブルを扱う - (゚∀゚)o彡 sasata299's blog
ä¸è¨ã®è¨äºãããããããã£ãã
ã ããããããé©åãªãã©ã³ã¶ã¯ã·ã§ã³ç®¡çãã¦ããã°
LAST_INSERT_ID 使ããªãã¦ããããªãï¼ã£ã¦æã£ãã®ã§ã¡ãã£ã¨æ¤è¨¼ãã¦ã¿ãã
æºå
mysql> CREATE TABLE num ( -> id bigint(20) unsigned NOT NULL DEFAULT '0' -> ) ENGINE=InnoDB; Query OK, 0 rows affected (0.53 sec) mysql> select @@tx_isolation; +-----------------+ | @@tx_isolation | +-----------------+ | REPEATABLE-READ | +-----------------+ 1 row in set (0.00 sec) mysql> select @@autocommit; +--------------+ | @@autocommit | +--------------+ | 0 | +--------------+ 1 row in set (0.00 sec)
試ã
update num set id = id + 1; select id from num;
LAST_INSERT_ID ãç¨ããªãä¸è¨ã®SQLã§ã
2人ã®ã¦ã¼ã¶ã¼ãæ¡çªããã±ã¼ã¹ã試ãã
select id from num; // 0 start transaction; update num set id = id + 1; start transaction; update num set id = id + 1; // å·¦è¨ãã³ããããããã¾ã§å¾ 㤠select id from num; // 1 commit; select id from num; // 2 commit;
ãã®ããã«é©åã«ãã©ã³ã¶ã¯ã·ã§ã³ç®¡çãã¦ããã°
åæå®è¡ã§ãåé¡ã¯èµ·ããªãã
ãã©ã³ã¶ã¯ã·ã§ã³ã使ããªãå ´å
ãã©ã³ã¶ã¯ã·ã§ã³ã使ããªãå ´åãã©ãã ãããã
ã¾ãLAST_INSERT_ID ã使ããªãæ¹ãã
select id from num; // 0 update num set id = id + 1; update num set id = id + 1; select id from num; // 2 select id from num; // 2
ãã©ã³ã¶ã¯ã·ã§ã³ã使ã£ã¦ãªãã®ã§å½ç¶ã®çµæã
ããã¯ãã¡ãã両è
id ãåãã«ãªã£ã¦ãã¾ã£ãã®ã§ã¾ãããã¿ã¼ã³ã
次ãLAST_INSERT_ID ã使ãå ´å
select id from num; // 0 update num set id = last_insert_id(id + 1); update num set id = last_insert_id(id + 1); select last_insert_id(); // 1 !!! select last_insert_id(); // 2 select id from num; // 2 select id from num; // 2
ã¨ããããã§ãLAST_INSERT_ID ã使ããã¨ã§ã
ãã©ã³ã¶ã¯ã·ã§ã³ã使ããã¨ã Isolation ãä¿ããã¦ãã¾ã£ãã
ãã®å ´åã® LAST_INSERT_ID ã¯ãAUTO INCREMENT ã¨é¢ä¿ã®ãã使ãæ¹ã§ã¯ãªãã
id ã®å¤ãã»ãã·ã§ã³å
ã§ä¿åãã¦ããããã®ãã¼ã«ã«å¤æ°ã®ããã«ä½¿ããã¦ããã®ããã¤ã³ãã ã
ã¨ããããã§æ¡çªãã¼ãã«ã¨ãã¦å½¹å²ãå
¨ããããªãã
ãã©ã³ã¶ã¯ã·ã§ã³ãªã㧠LAST_INSERT_ID ã使ããï¼
ä¸ç¨æã«ããã¯ããããå¿é
ããªããï¼
ãã¼ã¹ãããªã