如何优化插入和更新查询..
更新查询:
UPDATE `cp_sessions`
SET `last_activity` = 1389937578,
`user_id` = NULL,
`user_data` = 'a:3:{s:9:\"game_name\";s:5:\"poker\";s:3:\"utm\";N;s:5:\"url_1\";s:23:\"http://adda52merge.org/\";}'
WHERE `session_id` = '52b4aae2432db5c8236523e5357fb48d';
插入查询:
INSERT INTO `cp_sessions`
(`session_id`, `ip_address`, `user_agent`, `last_activity`)
VALUES (
'a68ca9a8d4b4f9462b4439bc60d05e91',
'192.168.1.235',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko', 1389937583);
将需要Query_time:1.654473
答案 0 :(得分:1)
如果您的表没有主键,请添加它。 如果你有一个session_id主键,它将是唯一的,不会有两个记录使用相同的session_id值。
ALTER TABLE `cp_sessions`
CHANGE COLUMN `session_id` `session_id` VARCHAR(32) NOT NULL FIRST,
ADD PRIMARY KEY (`session_id`);
如果您有重复的session_id值,请将其清除,如
CREATE TABLE blah LIKE cp_sessions;
ALTER TABLE `blah` CHANGE COLUMN `session_id` `session_id` VARCHAR(32) NOT NULL FIRST,
ADD PRIMARY KEY (`session_id`);
INSERT IGNORE INTO blah SELECT * FROM cp_sessions;
RENAME TABLE cp_sessions TO cp_session_old, blah TO cp_sessions;
这样你就可以继续做你正在做的事情, 或者您可以只有一个查询,而无需单独执行更新。
INSERT INTO `cp_sessions`
(`session_id`, `ip_address`, `user_agent`, `last_activity`)
VALUES (
'a68ca9a8d4b4f9462b4439bc60d05e91',
'192.168.1.235',
'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:27.0) Gecko', 1389937583)
ON DUPLICATE KEY UPDATE last_activity = VALUES(last_activity), user_agent = VALUES(user_agent);