使用join改进MySQL嵌套选择性能

时间:2016-07-14 06:07:28

标签: mysql performance

我已经看过很多样本来改进带有连接的MySQL嵌套选择,但我无法解决这个问题:

SELECT * FROM messages WHERE answer = 'SuccessSubscribed' AND phone NOT IN 
         (SELECT phone FROM messages WHERE answer = 'SuccessUnSubscribed');

查询查找已订阅但从未取消订阅的人。

表格结构:

CREATE TABLE `messages` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`phone` varchar(12) COLLATE utf8_persian_ci NOT NULL,
`content` varchar(300) COLLATE utf8_persian_ci NOT NULL,
`flags` int(10) unsigned NOT NULL DEFAULT '0',
`answer` varchar(50) COLLATE utf8_persian_ci DEFAULT NULL,
....,
PRIMARY KEY (`id`),
....
) ENGINE=InnoDB CHARSET=utf8 COLLATE=utf8_persian_ci

1 个答案:

答案 0 :(得分:1)

您可以NOT IN使用LEFT JOIN而不是NULL

SELECT M1.*
FROM messages M1
LEFT JOIN messages M2 ON M2.phone = M1.phone AND M2.answer = 'SuccessUnSubscribed'
WHERE M1.answer = 'SuccessSubscribed' AND M2.phone IS NULL