我尝试使用UPDATE ON DUPLICATE将一些记录添加到现有表中。 我的表:
CREATE TABLE IF NOT EXISTS `accounts` (
`accName` varchar(31) COLLATE utf8_unicode_ci NOT NULL,
`accId` mediumint(8) unsigned NOT NULL,
`twitchName` varchar(25) COLLATE utf8_unicode_ci DEFAULT '',
`challenge` tinyint(3) unsigned NOT NULL DEFAULT '0'
) ENGINE=MyISAM AUTO_INCREMENT=9 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT INTO `accounts` (`accName`, `accId`, `twitchName`, `challenge`) VALUES
('titi_love', 1, '', 1),
('oli1304', 2, '', 0),
('zeella', 3, '', 4),
('Snapfire', 4, '', 0),
('ncsbert', 5, 'ncsbert', 1),
('litmusdragon', 6, '', 1),
('Tsenk6a1', 7, '', 0),
('Azimuth69', 8, '', 0);
ALTER TABLE `accounts`
ADD PRIMARY KEY (`accName`), ADD UNIQUE KEY `accName` (`accName`), ADD UNIQUE KEY `accId` (`accId`);
ALTER TABLE `accounts`
MODIFY `accId` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=9;
我努力尝试但无法找到解决方案
accounts
中的现有记录无法更改accId
和accName
我只需添加新记录,如果accName
已存在,则更新归档twitchName
和{{1 }}
我有csv file,我尝试添加它:
challenge
或者那样:
CREATE TEMPORARY TABLE tmp LIKE accounts;
LOAD DATA INFILE '/www/phpfusion/test.csv' INTO TABLE tmp FIELDS TERMINATED BY ',' (`accName`, `twitchName`, `challenge`);
SHOW COLUMNS FROM tmp;
INSERT INTO `accounts` SELECT `accName`, `twitchName`, `challenge` FROM tmp ON DUPLICATE KEY UPDATE `accName`= VALUES(`accName`), `twitchName` = VALUES(`twitchName`), `challenge` = VALUES(`challenge`);
答案 0 :(得分:0)
这是对的!
CREATE TEMPORARY TABLE tmp LIKE accounts;
LOAD DATA LOCAL INFILE '/www/phpfusion/test.csv' INTO TABLE tmp FIELDS TERMINATED BY ',' (`accName`, `twitchName`, `challenge`);
INSERT INTO `accounts` (`accName`, `twitchName`, `challenge`) SELECT `accName`,`twitchName`, `challenge` FROM tmp ON DUPLICATE KEY UPDATE `accounts`.`twitchName` = tmp.twitchName, `accounts`.`challenge` = tmp.challenge;
DROP TEMPORARY TABLE tmp;