MySQLã§ãã¤ããã©ã¼ãã³ã¹ãªã¢ã¯ã»ã¹ã«ã¦ã³ã¿ã¼
MySQL ã使ã£ã¦ã¢ã¯ã»ã¹ã«ã¦ã³ã¿ã¼ãä½ã£ã¦ã¿ããã¨æãã¾ãã
ãã¼ãã¯
1, é«é(ã§ãããéãã«ã¦ã³ã¿ã®æ´æ°ã»åç
§ãéããã)
2, é«ä¿¡é ¼æ§ï¼å¤éã¢ã¯ã»ã¹ããã£ã¦ãå£ããªããä¸æ´åãèµ·ãããªãï¼
ã§ãã
æç´ã«å®è£ ãã¦ã¿ãã
ã¾ãã¯ç´æã§ã¶ã¯ã£ã¨ä½ãã¾ãã
ãã¼ãã«ä½æ
CREATE TABLE counter ( cnt int unsigned not null ) ENGINE=InnoDB;
åç §
SELECT cnt FROM counter;
æ´æ°
UPDATE counter SET cnt = cnt + 1;
ã¯ãã解説ã®å¿
è¦ããªãã»ã©ã·ã³ãã«ãªå
容ã ã¨æãã¾ãã
ã§ããããã®ã¢ã¯ã»ã¹ã«ã¦ã³ã¿ã¼ã¯é«éã¨ã¯è¨ãã¾ããã
ä½æ
ãã¨ããã¨ãMySQLã§ã¯æ´æ°ã®éã«å¯¾è±¡ã®è¡ã«ããã¯ããããã®ã§ã
ä¾ãã°åæã«100人ã¢ã¯ã»ã¹ããã£ãã¨ãããã100人åæã«ã¢ã¯ã»ã¹ã«ã¦ã³ã¿ã¼ã
æ´æ°ãããã®ã§ã¯ãªãã1人ãã¤å¦çããã¦ããã¾ãã
æå¾ã®äººã¯99人ã®æ´æ°ãçµããã¾ã§å¾
ã¤ãã§ãã
工夫ãã¦ã¿ã
ã¡ãã£ã¨å·¥å¤«ãã¦ã100人åæã«ã¢ã¯ã»ã¹ããããããªãã¹ã100人ãåæã«
ã¢ã¯ã»ã¹ã«ã¦ã³ã¿ã¼ãæ´æ°ããããã«ãã¦ã¿ã¾ãããã
ãã¼ãã«ä½æ
CREATE TABLE counter ( id int unsigned not null, cnt int unsigned not null, PRIMARY KEY (id) ) ENGINE=InnoDB;
åç §
SELECT SUM(cnt) FROM counter;
æ´æ°
UPDATE counter SET cnt = cnt + 1 WHERE id = RAND() * 100;
ãã¼ãã«ãåæåããéã«ä»¥ä¸ã id ã 1 ãã 100 ã¾ã§å®è¡ãã¦ããã¾ãã
INSERT INTO counter (id, cnt) VALUES(?, 0);
å
ã»ã©åé¡ã ã£ãã®ã¯ãæ´æ°ã»åç
§ããè¡ã1è¡ã ãã ã£ãããã§ãã
ã ãã ã«ã¦ã³ã¿ã¨ãã¦ä½¿ãè¡ã100è¡ã«å¢ãããæ´æ°ããéã¯
100è¡ã®ä¸ããã©ã³ãã ã«è¡ãé¸ã¶ãã¨ã§ãåæã¢ã¯ã»ã¹æã«ããã¯ãããè¡ã
åæ£ãã¦ãã¾ãã
UPDATEæã«ãã¼ãã«ãããã¯ããã®ã§ã¯ãªããè¡ã®ã¿ãããã¯ããInnoDBãã³ã¶ã¤ï¼
åç §ããæã¯ã100è¡ã«å ¥ã£ã¦ã cnt ããã¹ã¦ SUM() ãã¾ãã
ãã¤ãªã¼ã¢ã¯ã»ã¹æ°ãæ°ããã«ã¦ã³ã¿ã¼
ä¸æ¥ãã¨ã«ã¢ã¯ã»ã¹æ°ãæ°ããã«ã¦ã³ã¿ã¼ãä½ãã¾ãããã
ãã¼ãã«ä½æ
CREATE TABLE counter ( date date not null, id int unsigned not null, cnt int unsigned not null, PRIMARY KEY (date, id) ) ENGINE=InnoDB;
åç §
SELECT SUM(cnt) FROM counter WHERE date = CURRENT_DATE();
æ´æ°
INSERT INTO counter (date, id, cnt) VALUES (CURRENT_DATE(), RAND() * 100, 1) ON DUPLICATE KEY UPDATE cnt = cnt + 1;
ãã¼ãã«ã« date ã«ã©ã ã追å ãã¾ããã主ãã¼ã (date, id) ã¨ãªã£ã¦ãã¾ãã
(id, date) ã§ãªããã¨ã«æ³¨æãã¦ãã ãããé çªå¤§äºã§ãã
ä½æ
ããInnoDB ã§ã¯ä¸»ãã¼ã«è¨å®ããã«ã©ã ã«èªåçã«ã¤ã³ããã¯ã¹ãä½ããã¾ãã
åç
§å¦ç㧠where å¥ã« date ã«ã©ã ã使ããã¦ããã®ãè¦ã¦ä¸ããã
INDEX (date, id) 㯠where å¥ã« date ã®ã¿æå®ããã¦ãã¦ã使ãããã¤ã³ããã¯ã¹ã§ããã
INDEX (id, date) 㯠date ã®ã¿æå®ãã where å¥ã§ã¯ä½¿ããã¾ããã
æ´æ°å¦çã§ã¯ ON DUPLICATE KEY ã使ç¨ãã¦ãã¾ãã
æ¥ä»ãå¤ãã£ã¦æ´æ°å¯¾è±¡ã®è¡ãåå¨ããªããã° INSERT ããåå¨ãã¦ããã° UPDATE ã
è¡ãªã£ã¦ãã¾ãã
ä¸æ¦SELECT ãã¦ã¿ã¦ãããã° UPDATE ç¡ããã° INSERT ã¨ãã£ãå¦çãã¢ããªå´ã§
æ¸ããªãããã«ãã¾ããããããããæ㯠ON DUPLICATE KEY ã使ãã¾ãããã
ãã¯ã¹ããã¼ããã¯ãã®ã£ããããã¯ã¨ãã£ãåé¡ã«æ©ã¾ãããåå ã¨ãªãã¾ãã
çµãã
å®è·µãã¤ããã©ã¼ãã³ã¹MySQL 第3ç
- ä½è : Baron Schwartz,Peter Zaitsev,Vadim Tkachenko,èæ± ç èª(ç£è¨³),æ ªå¼ä¼ç¤¾ã¯ã¤ã¼ã
- åºç社/ã¡ã¼ã«ã¼: ãªã©ã¤ãªã¼ã¸ã£ãã³
- çºå£²æ¥: 2013/11/25
- ã¡ãã£ã¢: 大åæ¬
- ãã®ååãå«ãããã° (6件) ãè¦ã
å ¨é¨ãã®æ¬ããã®åã売ãã§ãã