Need help with sql query to find things with most specified tags

前提是你 提交于 2019-12-13 00:21:53

问题


Let's say I have the following tables:

TAGS

id: integer
name: string

POSTS

id: integer
body: text

TAGGINGS

id: integer
tag_id: integer
post_id: integer

How would I go about writing a query that selects all posts in order of the post containing the highest number of the following tags (name attribute of tags table): "Cheese", "Wine", "Paris", "Frace", "City", "Scenic", "Art"

See also: Need help with sql query to find things tagged with all specified tags (note: similar, but not a duplicate!)


回答1:


Unlike your linked question, you did not specify here that you needed to match ALL tags. This query works for ANY.

SELECT p.id, p.text, count(tg.id) as TagCount
    FROM Posts p 
        INNER JOIN Taggings tg 
            ON p.id = tg.post_id
        INNER JOIN Tags t 
            ON tg.tag_id = t.id
    WHERE t.name in ('Cheese', 'Wine', 'Paris', 'Frace', 'City', 'Scenic', 'Art')
    GROUP BY p.id, p.text
    ORDER BY TagCount DESC



回答2:


Try This:

   Select p.Id, p.Text, Count(*)
   From Posts p 
      Left Join (Taggings tg Join Tags t 
                    On t.Tag_Id = tg.Tag_Id
                       And t.name in     
                        ('Cheese', 'Wine', 'Paris', 
                         'Frace', 'City', 'Scenic', 'Art'))
         On tg.Post_Id = p.Post_Id
   Group By p.Id, p.text  
   Order By Count(*) Desc


来源:https://stackoverflow.com/questions/3876251/need-help-with-sql-query-to-find-things-with-most-specified-tags

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!