[英]MySQL: Grab rows where an ID isn't found in another table
Hope this makes sense, bad at this. 希望这是有道理的,不好的。
Here's the problem: I am trying to get a list of posts from an "articles" table and each article has a list of tags associated with them in another table called it "article_category_reference". 问题在于:我试图从“文章”表中获取帖子列表,每篇文章都有一个与其关联的标签列表,在另一个名为“article_category_reference”的表中。
Users block certain tags to customize their feed, so I want to filter them out of course. 用户会阻止某些标记来自定义其Feed,因此我希望将其过滤掉。 These will be in an array like (12 and 19 being tag ids): 这些将在一个数组中(12和19是标记ID):
$in = [0 => 12, 1 => 19];
Here's the current sample MySQL: 这是当前的MySQL示例:
SELECT a.`article_id`,
a.`title`,
a.`text`
FROM `articles` a
LEFT JOIN `article_category_reference` r
ON r.article_id = a.article_id
WHERE r.category_id NOT IN ( ?,? )
ORDER BY a.`date` DESC
LIMIT ?, ?
My problem is, it will filter out articles if they only have a single tag so I have it completely wrong. 我的问题是,如果他们只有一个标签,它会过滤掉文章,所以我完全错了。 I guess I can't simply join a table like that to filter? 我想我不能简单地加入这样的表来过滤?
You can perform a nested query. 您可以执行嵌套查询。 Very useful on Mysql 在Mysql上非常有用
SELECT a.`article_id`,
a.`title`,
a.`text`
FROM `articles` a
WHERE a.article_id IN (
SELECT r.`article_id`
FROM `article_category_reference` r
WHERE r.category_id NOT IN ( ?,? )
);
In simple terms go to article_category_reference get the all the ids but these and use these ids to query the articles table. 简单来说,转到article_category_reference获取所有id但是这些并使用这些id来查询articles表。
You could simply construct the query using a comma separated list of the values that you want to filter out, ie: 您可以使用要过滤掉的值的逗号分隔列表来构造查询,即:
WHERE r.category_id NOT IN ( 12, 19 )
I don't understand the part though where you say that 虽然你这么说,我不明白这个部分
it will filter out articles if they only have a single tag 如果文章只有一个标签,它会过滤掉文章
Maybe you could show a complete example with query, sample data, the result that you are getting and the result that you are expecting if this does not answer your question. 也许你可以展示一个完整的例子,包括查询,样本数据,你得到的结果,以及你没有回答你的问题所期望的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.