MariaDB:Select 一列中的字段 table 不在另一列的子集中 table

MariaDB: Select the fields from one column in one table that are not in a subset of another column from another table

更新:不要提供使用NOT EXISTS的答案。根据MariaDB"SQL statements that use the EXISTS condition in MariaDB are very inefficient since the sub-query is RE-RUN for EVERY row in the outer query's table."这个查询会用到很多,所以需要高效

我有两个表following:

CREATE TABLE `following` (
 `follower` int(1) unsigned NOT NULL,
 `followee` int(1) unsigned NOT NULL,
 PRIMARY KEY (`follower`,`followee`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

association_record

CREATE TABLE `association_record` (
 `user_id` int(1) unsigned NOT NULL,
 `post_id` int(1) unsigned NOT NULL,
 `answer_id` int(1) unsigned NOT NULL,
 `date_created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
 PRIMARY KEY (`user_id`,`post_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1

我想要的是 followee '5' 的 follower 没有 association_record 和 post '88'。下面的 SQL 是我从阅读其他 post 中得出的,但它并没有给我想要的结果:

select f.follower
from following f
left outer join association_record a
on f.follower = a.user_id
where f.followee = 5
and a.post_id = 88
and a.user_id is null
select f.follower from following f, response_record r where f.follower = r.user_id and f.followee = 5 and r.post_id = 88 and r.user_id is null

试试这个

为了简单起见,还是循序渐进为好。

那么,我们需要关注用户“5”的人吗?这是查询。

select follower from following where followee = 5;

现在我们需要知道哪些用户在 post '88' 上有记录。

select user_id from association_record where post_id=88;

现在我们需要以某种方式修复这两个查询。让我们开始吧:

select follower from following where followee = 5 and not exists (select user_id from association_record where post_id=88 and user_id=follower);

就是这样。在这里你有你的查询解释。

方法二:使用加入

SELECT follower
FROM following, association_record
WHERE follower=user_id
  AND followee = 5
  AND post_id=88
  AND user_id = null;

有些 SQL 引擎使用 !=,有些使用 <>。如果遇到问题,请尝试两者。

这是执行此操作的查询:

SELECT f.follower
FROM following f
LEFT OUTER JOIN association_record a
ON f.follower = a.user_id
AND a.poll_id = 88
WHERE f.followee = 5
AND a.user_id is null

解决后忘了post我的问题的解决方案,现在一个月后,我最终遇到了类似的问题,但没有参考原始解决方案;不再需要它了。

几乎不得不从头开始重新解决整个问题;这本来很难,因为我从来不明白解决方案是如何工作的。幸运的是,MySQL workbench 保留了所有查询的日志 运行,尝试查询来回答这个问题是我使用它的几次之一。

故事的寓意,别忘了post你的解决方案;你可能是为自己做的。