Select all projects that have matching tags

前端 未结 3 1050
粉色の甜心
粉色の甜心 2021-01-01 02:26

I\'m trying to find the most efficient way of dealing with this but I must tell you front-head I\'ve made a mess of it. Looked around SO and found nothing of relevance so he

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-01 02:40

    In any of the following cases, if you don't know the PROJECT.num/PROJECT_TO_TAGS.project_id, you'll have to join to the PROJECTS table to get the id value for finding out what tags it has associated.

    Using IN

    SELECT p.*
      FROM PROJECTS p
      JOIN PROJECTS_TO_TAGS pt ON pt.project_id = p.num
     WHERE pt.tag_id IN (SELECT x.tag_id
                           FROM PROJECTS_TO_TAGS x
                          WHERE x.project_id = 4)
    

    Using EXISTS

    SELECT p.*
      FROM PROJECTS p
      JOIN PROJECTS_TO_TAGS pt ON pt.project_id = p.num
     WHERE EXISTS (SELECT NULL
                     FROM PROJECTS_TO_TAGS x
                    WHERE x.project_id = 4
                      AND x.tag_id = pt.tag_id)
    

    Using JOINS (this the most efficient one!)

    The DISTINCT is necessary because JOINs risk duplicated data turning up in the resultset...

    SELECT DISTINCT p.*
      FROM PROJECTS p
      JOIN PROJECTS_TO_TAGS pt ON pt.project_id = p.num
      JOIN PROJECTS_TO_TAGS x ON x.tag_id = pt.tag_id
                             AND x.project_id = 4
    

提交回复
热议问题