多个否定子查询的更好方法

时间:2017-09-26 20:33:37

标签: mysql select in-subquery

我有几个像这样定义的表:

CREATE TABLE `member` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  ...
)

CREATE TABLE `members_to_delete` (
  `id` bigint(20),
  ...
)

CREATE TABLE `message` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `sender_id` bigint(20) NOT NULL,
  `recipient_id` bigint(20) DEFAULT NULL,
  ...
  CONSTRAINT `_FK1` FOREIGN KEY (`sender_id`) REFERENCES `member` (`id`),
  CONSTRAINT `_FK2` FOREIGN KEY (`recipient_id`) REFERENCES `member` (`id`)
)

members_to_delete表包含成员的子集。

只有在members_to_delete表中不存在sender_id和recipient_id时,我才想选择(并最终删除)消息表中的所有行。所以我提出了这个丑陋的问题:

SELECT id FROM message WHERE sender_id NOT IN (SELECT id FROM members_to_delete) 
AND recipient_id NOT IN (SELECT id FROM members_to_delete);  

我认为必须有一个更好的方法来编写这个查询,但我不确定它是什么。编写这种查询的更有效方法是什么?

1 个答案:

答案 0 :(得分:2)

您可以将Return row only if value doesn't exist中的技术用于多列。

SELECT m.id
FROM message AS m
LEFT JOIN members_to_delete AS d
ON d.id IN (m.sender_id, m.recipient_id)
WHERE d.id IS NULL