[英]sql self join and many to many relationship
我有一個稱為類別的表,一條記錄可以有一個父母或一個孩子和這個類別。 類別表是通過post_category與帖子建立多對多關系的。
category[id, name category_id]
posts[id,title, body....]
post_cats[id,post_id,category_id]
樣本數據
category
id name category_id
1 xxxx 0
2 yyyy 0
3 ZZZZ 1
4 WWWW 1
5 AAAA 2
6 BBBB 2
posts
id title body
1 aaaaaaaaaa
2 bbbbbbbbbbbbbb
3 ccccccccccccccc
4 ddddddddddd
post_cats
id post_id category_id
1 1 3
2 1 4
3 2 5
4 2 6
5 2 3
類別記錄1的帖子為3,而記錄2的帖子為2,我想統計屬於類別名稱“ xxxx”的所有帖子,或者只是想對屬於每個父類別的所有帖子進行計數,並對其子類別進行計數。
select post_id
from post_category
group by post_id
having count(*) = (select count(*) from category)
只需使用arel gem嘗試以下方案:
class ParentCategory < ...
has_many :categories
scope :posts, -> do
Post.joins(:categories)
.where(Post.arel_table[:id].eq(Category.arel_table[:post_id])
.and(Category.arel_table[:parent_category_id].eq(arel_table[:id])))
end
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.