ÉîÈëmysql "ON DUPLICATE KEY UPDATE" Óï·¨µÄ·ÖÎö
Èç¹ûÔÚINSERTÓï¾äĩβָ¶¨ÁËON DUPLICATE KEY UPDATE£¬²¢ÇÒ²åÈëÐкó»áµ¼ÖÂÔÚÒ»¸öUNIQUEË÷Òý»òPRIMARY KEYÖгöÏÖÖظ´Öµ£¬ÔòÔÚ³öÏÖÖظ´ÖµµÄÐÐÖ´ÐÐUPDATE£»Èç¹û²»»áµ¼ÖÂΨһֵÁÐÖظ´µÄÎÊÌ⣬Ôò²åÈëÐÂÐС£
ÀýÈ磬Èç¹ûÁÐ a Ϊ Ö÷¼ü »ò ÓµÓÐUNIQUEË÷Òý£¬²¢ÇÒ°üº¬Öµ1£¬ÔòÒÔÏÂÁ½¸öÓï¾ä¾ßÓÐÏàͬµÄЧ¹û£º
INSERT INTO TABLE (a,c) VALUES (1,3) ON DUPLICATE KEY UPDATE c=c+1; UPDATE TABLE SET c=c+1 WHERE a=1;Èç¹ûÐÐ×÷ΪмǼ±»²åÈ룬ÔòÊÜÓ°ÏìÐеÄÖµÏÔʾ1£»Èç¹ûÔÓеļǼ±»¸üУ¬ÔòÊÜÓ°ÏìÐеÄÖµÏÔʾ2¡£
Õâ¸öÓï·¨»¹¿ÉÒÔÕâÑùÓÃ:
Èç¹ûINSERT¶àÐмǼ(¼ÙÉè a ΪÖ÷¼ü»ò a ÊÇÒ»¸ö UNIQUEË÷ÒýÁÐ):
INSERT INTO TABLE (a,c) VALUES (1,3),(1,7) ON DUPLICATE KEY UPDATE c=c+1;
Ö´Ðкó, c µÄÖµ»á±äΪ 4 (µÚ¶þÌõÓëµÚÒ»ÌõÖظ´, c ÔÚÔÖµÉÏ+1).
INSERT INTO TABLE (a,c) VALUES (1,3),(1,7) ON DUPLICATE KEY UPDATE c=VALUES(c);Ö´Ðкó, c µÄÖµ»á±äΪ 7 (µÚ¶þÌõÓëµÚÒ»ÌõÖظ´, c ÔÚÖ±½ÓÈ¡Öظ´µÄÖµ7).
×¢Ò⣺ON DUPLICATE KEY UPDATEÖ»ÊÇMySQLµÄÌØÓÐÓï·¨£¬²¢²»ÊÇSQL±ê×¼Óï·¨£¡
Õâ¸öÓï·¨ºÍÊʺÏÓÃÔÚÐèÒª ÅжϼǼÊÇ·ñ´æÔÚ,²»´æÔÚÔò²åÈë´æÔÚÔò¸üеij¡¾°.
INSERT INTO .. ON DUPLICATE KEY¸üжàÐмǼ
Èç¹ûÔÚINSERTÓï¾äĩβָ¶¨ÁËON DUPLICATE KEY UPDATE£¬²¢ÇÒ²åÈëÐкó»áµ¼ÖÂÔÚÒ»¸öUNIQUEË÷Òý»òPRIMARY KEYÖгöÏÖÖظ´Öµ£¬ÔòÖ´ÐоÉÐÐUPDATE£»Èç¹û²»»áµ¼ÖÂΨһֵÁÐÖظ´µÄÎÊÌ⣬Ôò²åÈëÐÂÐС£ÀýÈ磬Èç¹ûÁÐa±»¶¨ÒåΪUNIQUE£¬²¢ÇÒ°üº¬Öµ1£¬ÔòÒÔÏÂÁ½¸öÓï¾ä¾ßÓÐÏàͬµÄЧ¹û£º
INSERT INTO TABLE (a,b,c) VALUES (1,2,3) ON DUPLICATE KEY UPDATE c=c+1; UPDATE TABLE SET c=c+1 WHERE a=1;Èç¹ûÐÐ×÷ΪмǼ±»²åÈ룬ÔòÊÜÓ°ÏìÐеÄֵΪ1£»Èç¹ûÔÓеļǼ±»¸üУ¬ÔòÊÜÓ°ÏìÐеÄֵΪ2¡£
Èç¹ûÄãÏëÁ˽â¸ü¶à¹ØÓÚINSERT INTO .. ON DUPLICATE KEYµÄ¹¦ÄÜ˵Ã÷£¬Ïê¼ûMySQL²Î¿¼Îĵµ£º13.2.4. INSERTÓï·¨
ÏÖÔÚÎÊÌâÀ´ÁË£¬Èç¹ûINSERT¶àÐмǼ£¬ ON DUPLICATE KEY UPDATEºóÃæ×ֶεÄÖµÔõôָ¶¨£¿ÒªÖªµÀÒ»ÌõINSERTÓï¾äÖÐÖ»ÄÜÓÐÒ»¸öON DUPLICATE KEY UPDATE£¬µ½µ×Ëû»á¸üÐÂÒ»ÐмǼ£¬»¹ÊǸüÐÂËùÓÐÐèÒª¸üеÄÐС£Õâ¸öÎÊÌâÀ§ÈÅÁËÎҺܾÃÁË£¬ÆäʵʹÓÃVALUES()º¯ÊýÒ»ÇÐÎÊÌⶼ½â¾öÁË¡£
¾Ù¸öÀý×Ó£¬×Ö¶Îa±»¶¨ÒåΪUNIQUE£¬²¢ÇÒÔÊý¾Ý¿â±ítableÖÐÒÑ´æÔڼǼ(2,2,9)ºÍ(3,2,1)£¬Èç¹û²åÈë¼Ç¼µÄaÖµÓëÔÓмǼÖظ´£¬Ôò¸üÐÂÔÓмǼ£¬·ñÔò²åÈëÐÂÐУº
INSERT INTO TABLE (a,b,c) VALUES (1,2,3), (2,5,7), (3,3,6), (4,8,2) ON DUPLICATE KEY UPDATE b=VALUES(b);ÒÔÉÏSQLÓï¾äµÄÖ´ÐУ¬·¢ÏÖ(2,5,7)ÖеÄaÓëÔÓмǼ(2,2,9)·¢ÉúΨһֵ³åÍ»£¬ÔòÖ´ÐÐON DUPLICATE KEY UPDATE£¬½«ÔÓмǼ(2,2,9)¸üгÉ(2,5,9)£¬½«(3,2,1)¸üгÉ(3,3,1)£¬²åÈëмǼ(1,2,3)ºÍ(4,8,2)
×¢Ò⣺ON DUPLICATE KEY UPDATEÖ»ÊÇMySQLµÄÌØÓÐÓï·¨£¬²¢²»ÊÇSQL±ê×¼Óï·¨£¡
ÍƼöÐÅÏ¢
ÈÈÃÅÐÅÏ¢
- nohup: redirecting stderr to stdou....
- ʹÓÃlog_formatΪNginx·þÎñÆ÷ÉèÖøüÏêϸµÄÈÕÖ¾¸ñʽ
- jquery easyUI--dataGrid-Json
- [Ô´´]·ÂGoogle Reader¡¢ÐÂÀË΢²©¡¢ÌÚѶ΢²©µ....
- ÀûÓÃKeepalived+mysql¹¹½¨¸ß¿ÉÓÃMySQLË«Ö÷×Ô¶....
- Nginx+keepalivedʵÏÖ¸ºÔؾùºâºÍË«»úÈȱ¸¸ß¿ÉÓÃ
- jqueryʵÏÖÒ³Ãæ¼ÓÔؽø¶ÈÌõ
- Rolling cURL: PHP²¢·¢×î¼Ñʵ¼ù
- codeigniter ·ÓÉÖÕ¼«ÓÅ»¯(url rewrite)
- linuxÏÂÉèÖÃsshÎÞÃÜÂëµÇ¼
ÆÀÂÛ