【问题标题】:Select records that match a field, but order them by a different field选择与字段匹配的记录,但按不同字段排序
【发布时间】:2013-08-23 05:21:26
【问题描述】:

我的表格如下所示:

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 语句获得全局标签计数?

【问题讨论】:

    标签: mysql sql sqlite select count


    【解决方案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
    

    【讨论】:

      【解决方案2】:

      Sql fiddle at

      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
      

      如果需要可以添加

      【讨论】:

        【解决方案3】:

        在 SQLite 中,使用子查询:

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-08-19
          • 2019-03-29
          • 1970-01-01
          • 1970-01-01
          • 2018-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多