从查询中获取X个最受欢迎的标签

时间:2017-08-29 19:45:36

标签: php mysql

$query = "SELECT tag.name, tag.id
        FROM #__k2_tags as tag
        LEFT JOIN #__k2_tags_xref AS xref ON xref.tagID = tag.id
        WHERE xref.itemID IN (".implode(',', $IDs).")
        AND tag.published = 1";
xref.tagID中的

是标签ids例如:tagID:42是100次,tagID:15是90次,tagID:56是10次,我想先显示42然后再显示15然后56(我想要多少标签是在xref.tagID和顺序)

2 个答案:

答案 0 :(得分:1)

试试这个:

$query = "
SELECT *
FROM (
    SELECT tag.name, tag.id, count(xref.id) AS tagCount
    FROM #__k2_tags as tag
    LEFT JOIN #__k2_tags_xref AS xref ON xref.tagID = tag.id
    WHERE xref.itemID IN (".implode(',', $IDs).") AND tag.published = 1
    GROUP BY tag.name, tag.id
)
ORDER BY tagCount";

子查询中的GroupBy允许您计算每种标记类型的标记出现次数。
主查询需要按聚合值tagCount排序。

答案 1 :(得分:0)

您可以尝试使用group by功能:

"SELECT  tag.id, count(*)
        FROM #__k2_tags as tag
        LEFT JOIN #__k2_tags_xref AS xref ON xref.tagID = tag.id
        WHERE xref.itemID IN (".implode(',', $IDs).")
        AND tag.published = 1
GROUP BY tag.id";