选择与字段匹配的记录,但按其他字段排序

时间:2013-08-21 00:53:36

标签: mysql sql sqlite select count

我的表格如下:

tags: id, name, description
tag_relations: tag, item

item引用另一个表的id,tag引用tags表的id。

所以我正在尝试选择最常用的标签:

SELECT t.*, COUNT(r.item) AS item_count
FROM tag_relations as r
INNER JOIN tags as t ON r.tag = t.id
GROUP BY t.id
ORDER BY item_count

有效,但如果我添加

WHERE t.id = ?

item_count始终为1 ...

有没有什么方法我可以使用只选择1个标签或一组特定标签的select语句来计算全局标签?

3 个答案:

答案 0 :(得分:1)

我无法访问MySQL,但我确实可以访问Microsoft SQLServer。我意识到你的标签指定了mysql。即便如此,您提出的查询在SQLServer中失败,错误

Msg 8120, Level 16, State 1, Line 1
Column 'tags.name' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

...因为select t。*不包含在group by子句中。

无论如何,为了解决您的具体问题,您可以在使用交叉连接选择特定记录的同时获得全局数字...

select
    t.*
    , vTagRelations.GlobalCountOfTagRelations
    , vTags.GlobalCountOfTags
from
    tags t
    cross join (select
        count(tag_relations.tag) as GlobalCountOfTagRelations
    from
        tag_relations) vTagRelations
    cross join (select
        count(tags.id) as GlobalCountOfTags
    from
        tags) vTags
where
    t.id = 2

答案 1 :(得分:1)

的小提琴

http://www.sqlfiddle.com/#!2/ba97d/1

SELECT name,count(item) as counter_item
FROM tag_relations 
INNER JOIN tags ON 
tag_relations.tag =tags.id
order by counter_item

where tags.id=1

如果需要可以添加

答案 2 :(得分:1)

在SQLite中,使用子查询:

SELECT *, (SELECT COUNT() FROM tag_relations WHERE tag=tags.id) AS item_count FROM tags WHERE id=?;