0

Table "Post":

id active
382857 true
382851 true
383015 true
382906 true
382909 true

Table "PosTags":

post_id tag_id
382857 480
382857 953
382857 9230
382857 9232
382857 56677
382857 107901

The first table stores posts, while the second one stores postags for each post. I need to gather information regarding posts and tags and I'm using the following query:

SELECT id 
FROM posts
WHERE id NOT IN (SELECT post_id FROM post_tags WHERE tag_id = 55723)
LIMIT 8

Problem is that this query won't retrieve posts that have no postags.

Can you help me fixing this query?

3
  • Can you please attach output of EXPLAIN and DDL you've used to create mentioned tables? Commented May 27, 2022 at 10:41
  • QUERY PLAN Limit (cost=460.44..460.90 rows=8 width=5) -> Seq Scan on pgvk_material (cost=460.44..11135.67 rows=187409 width=5) Filter: (NOT (hashed SubPlan 1)) SubPlan 1 -> Index Scan using fki_pgvk_material_tag_id_fkey on pgvk_material_tag (cost=0.43..460.13 rows=124 width=4) Index Cond: (tag_id = 55723) Commented May 27, 2022 at 10:57
  • create table posts ( id bigserial primary key, ..... ); create table post_tags ( post_id bigint not null constraint post_tags_post_id_foreign references posts on update cascade on delete cascade, tag_id bigint not null constraint post_tags_tag_id_foreign references tags on update cascade on delete cascade, primary key (post_id, tag_id) ); Commented May 27, 2022 at 11:01

1 Answer 1

1

Try with this query:

SELECT posts.id,
       posts.active
FROM      posts
LEFT JOIN posttags
       ON posts.id = posttags.post_id
      AND posttags.tag_id = 9230
WHERE posttags.post_id IS NULL

Basically it looks for the posts which have the specific tag_id you don't want and excludes them from the match of the posts table using a LEFT JOIN.

If you have more than one tag you want to exclude, it is sufficient to change the second part of the JOIN condition into the following:

AND posttags.tag_id IN [9230, ...]

SQL Fiddle here.

Sign up to request clarification or add additional context in comments.

2 Comments

exelent solution
If this answer has helped you, consider ticking it as the solution of your post. @Brain2xml

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.