mysql 中使用INSERT … ON DUPLICATE KEY UPDATE(insert ignore)

來源:互聯網
上載者:User

這個語句非常好,

例如:

IF(SELECT * FROM test.relation_seo_keyword_webpage WHERE keywordid = 1 AND webpageid =1)
{
UPDATE test.relation_seo_keyword_webpage
SET positionCount= positionCount+1,searchCount = searchCount +1
WHERE keywordid = 1 AND webpageid =1;
}
ELSE
{
INSERT INTO test.relation_seo_keyword_webpage(keywordid,webpageid,positionCount,searchCount) VALUES (1,1,1,1);
}

三條SQL,現在如果用INSERT ... ON DUPLICTE KEY UPDATE來實現就方便多了

INSERT INTO test.relation_seo_keyword_webpage VALUES(1,1,1,1) 
ON DUPLICATE KEY UPDATE keywordid=1,webpageid=1,positionCount= positionCount+1,searchCount = searchCount +1;

最好是指定列名

INSERT INTO test.relation_seo_keyword_webpage(keywordid,webpageid,positionCount,searchCount) VALUES(1,1,1,1) 
ON DUPLICATE KEY UPDATE keywordid=1,webpageid=1,positionCount= positionCount+1,searchCount = searchCount +1;

注意,如果表中keywordid和webpageid在表中不是主鍵(組合主鍵),如果執行以上語句就會插入重複資料,所以需要主鍵。

修改表的主鍵語句:

ALTER TABLE test.relation_seo_keyword_webpage ADD(CONSTRAINT PRIMARY KEY(keywordid,webpageid));

注意我的mysql版本是:5.0.51b

建表語句:

--
-- Table structure for table `relation_seo_keyword_webpage`
--

DROP TABLE IF EXISTS `relation_seo_keyword_webpage`;
SET @saved_cs_client = @@character_set_client;
SET character_set_client = utf8;
CREATE TABLE `relation_seo_keyword_webpage` (
`keywordid` int(11) NOT NULL,
`webpageid` int(11) NOT NULL,
`positionCount` int(10) unsigned zerofill default '0000000000',
`searchCount` int(10) unsigned zerofill default '0000000000',
PRIMARY KEY (`keywordid`,`webpageid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
SET character_set_client = @saved_cs_client;

--
-- Dumping data for table `relation_seo_keyword_webpage`
--

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.