多个否定子查询的更好方法
Better approach for multiple negated subqueries
我有几个 table 是这样定义的:
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 table 包含一部分成员。
我想 select(并最终删除)消息 table 中的所有行,前提是 sender_id 和 recipient_id 都不存在于 members_to_delete table。所以我想出了这个丑陋的查询:
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);
我想一定有更好的方法来编写这个查询,但我不确定它是什么。编写此类查询的更有效方法是什么?
您可以对多列使用 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
我有几个 table 是这样定义的:
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 table 包含一部分成员。
我想 select(并最终删除)消息 table 中的所有行,前提是 sender_id 和 recipient_id 都不存在于 members_to_delete table。所以我想出了这个丑陋的查询:
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);
我想一定有更好的方法来编写这个查询,但我不确定它是什么。编写此类查询的更有效方法是什么?
您可以对多列使用 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