获取连接表中没有匹配记录的记录

时间:2018-01-04 05:33:31

标签: mysql sql subquery

我有以下2个MySQL数据库表。

CREATE TABLE `leads` (
  `lead_id` int(11) NOT NULL,
  `fname` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
  `lname` varchar(100) CHARACTER SET utf8 DEFAULT NULL,
  `email` varchar(200) CHARACTER SET utf8 DEFAULT NULL,
  `phone_mobile` varchar(15) CHARACTER SET utf8 DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `leads`
  ADD PRIMARY KEY (`lead_id`);

ALTER TABLE `leads`
  MODIFY `lead_id` int(11) NOT NULL AUTO_INCREMENT;

CREATE TABLE `card_results` (
  `card_result_id` int(11) NOT NULL,
  `lead_id` int(11) NOT NULL,
  `success` tinyint(1) NOT NULL DEFAULT '0',
  `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `card_results`
  ADD PRIMARY KEY (`card_result_id`),
  ADD KEY `created` (`created`),
  ADD KEY `success` (`success`);

ALTER TABLE `card_results`
  MODIFY `card_result_id` int(11) NOT NULL AUTO_INCREMENT;

ALTER TABLE `card_results`
  ADD CONSTRAINT `FK_card_results_lead_id` FOREIGN KEY (`lead_id`) REFERENCES `leads` (`lead_id`) ON DELETE CASCADE ON UPDATE CASCADE,
COMMIT;

我希望找到leads表中过去3个月card_results表中没有匹配记录的所有记录。

这两个表与外键'lead_id'

相关

我的查询如下:

SELECT l.lead_id
FROM leads l
WHERE 
    (SELECT COUNT(*) 
     FROM card_results c
     WHERE success = 1
       AND created >= NOW()-INTERVAL 3 MONTH
       AND c.lead_id = l.lead_id) = 0

查询运行有点慢,我想优化它。

是否有其他方法可以达到相同的效果。

2 个答案:

答案 0 :(得分:2)

您可以使用LEFT加入IS NULL,确保您的过滤器应该用于ON子句而不是WHERE

SELECT l.lead_id
FROM leads l
LEFT JOIN card_results c 
       ON l.lead_id = c.lead_id
       AND c.created >= NOW()-INTERVAL 3 MONTH
       AND c.success = 1
WHERE c.lead_id IS NULL

答案 1 :(得分:1)

通过以下方式之一尝试:

使用NOT IN

SELECT l.lead_id
FROM leads l
WHERE l.lead_id NOT IN (
    SELECT c.lead_id 
    FROM card_results c
    WHERE success = 1
    AND created >= NOW()-INTERVAL 3 MONTH)

使用JOINIS NULL

SELECT l.lead_id
FROM leads l
LEFT JOIN card_results c ON c.lead_id = l.lead_id
    AND c.success = 1
    AND created >= NOW()-INTERVAL 3 MONTH
WHERE c.lead_id IS NULL

使用NOT EXISTS

SELECT l.lead_id
FROM leads l
WHERE NOT EXISTS 
    (SELECT 1
     FROM card_results c
     WHERE success = 1
       AND created >= NOW()-INTERVAL 3 MONTH
       AND c.lead_id = l.lead_id)