如果您希望它们按最高标签首选项排序,则如下所示:-
SELECT Article.id, Article.title, Sub1.MaxPreference
FROM Article
INNER JOIN
(
SELECT Article.id, MAX(Tags.preference) AS MaxPreference
FROM Article
INNER JOIN ArticleTags ON Article.id = ArticleTags.articleid
INNER JOIN Tags ON ArticleTags.tagid = Tags.id
GROUP BY Article.id
) Sub1
ON Article.id = Sub1.id
ORDER BY Sub1.MaxPreference DESC
将其限制为仅考虑几个标签:-
SELECT Article.id, Article.title, Sub1.MaxPreference
FROM Article
LEFT OUTER JOIN
(
SELECT Article.id, MAX(Tags.preference) AS MaxPreference
FROM Article
INNER JOIN ArticleTags ON Article.id = ArticleTags.articleid
INNER JOIN Tags ON ArticleTags.tagid = Tags.id
WHERE Tags.tagname IN ('mobile','tech')
GROUP BY Article.id
) Sub1
ON Article.id = Sub1.id
ORDER BY Sub1.MaxPreference DESC
如果您希望它们按偏好总和排序,则如下所示:-
SELECT Article.id, Article.title, Sub1.SumPreference
FROM Article
INNER JOIN
(
SELECT Article.id, SUM(Tags.preference) AS SumPreference
FROM Article
INNER JOIN ArticleTags ON Article.id = ArticleTags.articleid
INNER JOIN Tags ON ArticleTags.tagid = Tags.id
GROUP BY Article.id
) Sub1
ON Article.id = Sub1.id
ORDER BY Sub1.SumPreference DESC