0

我正在使用以下结构:

Table Article:
id
title

Table ArticleTags:
id
articleid
tagid

Table Tags:
id
tagname
preferenece [0-5]

现在我需要根据多个标签对文章进行排序。是否可以使用mysql单查询

例子:

article A is tagged by following tags and preference
pc 2
mobile 3
tech 1

article B is tagged by following tags and preference
tech 3
php 2
grails 4
mobile 2

现在,如果我想按标签排序 - 移动和技术,文章 B 将排名第一。如果我只按移动文章A排序,将排名第一。

4

3 回答 3

1

articletags由于标签对于不同的文章具有不同的权重恕我直言,在表格中而不是表格中具有偏好(权重)列是很自然的tags。否则,您将在标签中使用相同名称但权重不同的多个条目。

因此,我建议您更改架构

CREATE TABLE articletags
  (`id` int, `articleid` int, `tagid` int, `preference` int);
CREATE TABLE tags
  (`id` int, `tagname` varchar(32));

现在获得每篇文章的权重总和并应用顺序的所有其他规则都是相同的

SELECT a.* 
  FROM article a JOIN
(
  SELECT articleid, SUM(at.preference) total_preference
    FROM articletags at JOIN tags t
      ON at.tagid = t.id
   WHERE t.tagname IN ('mobile', 'tech')
   GROUP BY articleid
) q ON a.id = q.articleid
 ORDER BY q.total_preference DESC

这是SQLFiddle演示

于 2013-06-25T10:11:38.783 回答
1

表的关系不是很清楚,我在想这样的关系:

Article Table (id) <= (articleid) ArticleTags Table (tagid) => (id) Tags Table

根据您给定的标准,看起来SUMofpreference用于对输出进行排序。

所以我最终得到了这个查询:

SELECT A.title
    , SUM(T.preference) AS preferenceSum
    FROM Tags T
    INNER JOIN ArticleTags AT ON T.tagid = T.id
    INNER JOIN Article A ON A.id = AT.articleid
    WHERE T.tagname IN ('mobile', 'tech')
    GROUP BY A.id
    ORDER BY preferenceSum DESC;

而且也不清楚有什么tags不同preference。从您的问题来看,mobiletech存在不同的preference. 或者我们在这里缺少一些表格。

于 2013-06-25T09:00:38.287 回答
1

如果您希望它们按最高标签首选项排序,则如下所示:-

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
于 2013-06-25T09:16:11.323 回答