选择在联结表中具有多个值的行

时间:2018-02-22 17:18:51

标签: postgresql junction-table

我有三张桌子:

posts (id, content)
posts_tags (posts_id, tags_id)
tags (id, tag)

如何选择所有包含(至少)2个特定标签的帖子(比如说标识为1和2的标签)?

例如,帖子表:

  id   content   
 ---- ------- 
  1    post1  
  2    post2  
  3    post3  

标签表:

  id   tag   
 ---- ------ 
  1    tag1  
  2    tag2  
  3    tag3  

posts_tags表:

  posts_id   tags_id  
 ---------- --------- 
  1          1        
  1          2        
  2          1        
  3          1        
  3          2        
  3          3        

然后我期待以下结果:

  id   content  
 ---- --------- 
  1    post1    
  3    post3   

发布ID 3(因为它有标签1,2和3)并发布id为1(因为它的标签有id 1和2)但不是post 2,因为它没有标签id 2。

假设我无法更改表格结构。

2 个答案:

答案 0 :(得分:1)

SELECT * 
FROM posts p
JOIN posts_tags pt ON pt.posts_id = p.id
WHERE pt.tags_id IN (1,2);


SELECT * 
FROM posts p
JOIN posts_tags pt ON pt.posts_id = p.id
WHERE pt.tags_id = 1 OR pt.tags_id = 2;


SELECT * 
FROM posts p
JOIN posts_tags pt ON pt.posts_id = p.id
WHERE pt.tags_id = 1 AND pt.tags_id = 2;

编辑:又快又脏

WITH j AS (
SELECT  pt.posts_id AS post, 
    p.content AS content, 
    STRING_AGG(pt.tags_id::TEXT,',') AS agg
FROM posts p
JOIN posts_tags pt ON pt.posts_id = p.id
GROUP BY pt.posts_id, p.content
)
SELECT post,content
FROM j
WHERE STRING_TO_ARRAY(agg,',') @> ('{2,1}'::TEXT[])

答案 1 :(得分:0)

找到我自己的问题的答案:

SELECT posts.*
FROM posts
INNER JOIN posts_tags ON posts_tags.posts_id = posts.id
INNER JOIN tags ON tags.id = posts_tags.tags_id
WHERE tags.id IN (1, 2)
GROUP BY posts.id
HAVING COUNT(*) > 1