我有一些这样定义的表:
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也没有收件人。所以我想出了这个丑陋的查询:
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
关于mysql - 多个否定子查询的更好方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46435328/