0

我的表如下所示:

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

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

4

3 回答 3

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
于 2013-08-21T01:10:06.527 回答
1

Sql 小提琴在

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

如果需要可以添加

于 2013-08-21T02:43:18.873 回答
1

在 SQLite 中,使用子查询:

SELECT *, (SELECT COUNT() FROM tag_relations WHERE tag=tags.id) AS item_count FROM tags WHERE id=?;
于 2013-08-23T11:19:37.370 回答