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
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