Getting related tags from SQL Server when you have filtered down

前端 未结 3 1862
春和景丽
春和景丽 2021-02-06 18:47

I asked this question before and got a great working answer.

what is the query to get "related tags" like in stack overflow

but i realized that SOF ac

3条回答
  •  别跟我提以往
    2021-02-06 19:13

    I'd use something like this as the first version. @FirstTagID and @SecondTagID must be sorted by ID. You can query on more tags by adding more joins to the inner query.

    SELECT tagName
    FROM tags
    WHERE id IN (
        SELECT tagID
        FROM tagsBridge
        WHERE linkID IN (
            SELECT t1.linkID
            FROM
                tagsBridge t1
                JOIN tagsBridge t2 ON t2.linkID=t1.linkID AND t2.tagID > t1.tagID
            WHERE t1.tagID=@FirstTagID AND t2.tagID=@SecondTagID
        )
        AND tagID!=@FirstTagID AND tagID!=@SecondTagID
    )
    

    Or if you want to include the number of links:

    SELECT t.tagName, count(*)
    FROM 
        tags t
        JOIN tagsBridge tb ON tb.tagID = t.id
    WHERE
        tb.linkID IN (
            SELECT t1.linkID
            FROM
                tagsBridge t1
                JOIN tagsBridge t2 ON t2.linkID=t1.linkID AND t2.tagID > t1.tagID
            WHERE t1.tagID=@FirstTagID AND t2.tagID=@SecondTagID
        )
        AND t.tagID!=@FirstTagID AND t.tagID!=@SecondTagID
    GROUP BY t.tagName
    

    The same for three tags:

    SELECT t.tagName, count(*)
    FROM 
        tags t
        JOIN tagsBridge tb ON tb.tagID = t.id
    WHERE
        tb.linkID IN (
            SELECT t1.linkID
            FROM
                tagsBridge t1
                JOIN tagsBridge t2 ON t2.linkID=t1.linkID AND t2.tagID > t1.tagID
                JOIN tagsBridge t3 ON t3.linkID=t2.linkID AND t3.tagID > t2.tagID
            WHERE t1.tagID=@FirstTagID AND t2.tagID=@SecondTagID AND t3.tagID=@ThirdTagID
        )
        AND t.tagID!=@FirstTagID AND t.tagID!=@SecondTagID AND t.tagID!=@ThirdTagID
    GROUP BY t.tagName
    

提交回复
热议问题