【问题标题】:How to display the number or rows that belong to a category for every category in SQL如何在 SQL 中为每个类别显示属于某个类别的数量或行数
【发布时间】:2013-10-10 07:18:28
【问题描述】:

我有一个视频类别表和一个视频记录表。视频类别中的列是 id 和 cname,在视频录制中有一个类别列。我想显示每个类别有多少视频记录。

我试过了

select vc.cname, count(*) as catcount
from video_categories vc, video_recordings vr
where vc.cname = vr.category
group by vc.id

但这仅返回 id 为 0 的第一个类别的记录数。 我需要它们来显示所有这些。

我创建了这样的表格

Video_Recordings (
recording_id,
director,
title,
category,
image_name,
duration,
rating,
year_released,
price,
stock_count
);

Video_Categories (
id,
name
);

Video_Actors (
id,
name,
recording_id
);

使用正确的数据类型,然后我用

加载它们
Load Data local Infile
' D:/files...' into table
video_recodrings fields terminated by '\t' lines terminated by '\n';

当我这样做并检查表格时,表格是否正确。

【问题讨论】:

  • 按正确的方式分组。算对了。并且不要使用隐式连接。

标签: mysql sql


【解决方案1】:

您必须按 vc.name 对它们进行分组

select vc.cname, count(*) as catcount from video_categories as vc, video_recordings as vr where vc.cname = vr.category group by vc.name

【讨论】:

    【解决方案2】:

    嘿,你想要按类别的行数,然后按 按 vc.cname 分组

    select vc.cname, count(*) as catcount
    from video_categories vc
    inner join video_recordings vr on vc.cname = vr.category
    group by vc.cname
    

    【讨论】:

    • 当我这样做时,当有 6 个类别时,它仍然只显示 1 个类别
    • 没有尾随空格
    • 请用示例数据添加您的表结构因为我不认为这是一个查询问题
    • 我添加了我的表结构
    【解决方案3】:

    您的查询运行良好,只需稍作改动。检查http://sqlfiddle.com/#!2/2e060/1

    【讨论】:

      【解决方案4】:

      您可能将错误的列与Video_Recordings.category 匹配。我可能错了,但只有id = 0 被返回的事实对我来说意味着category 列是一个整数并且是对Video_Categories.id(而不是Video_Categories.name)的引用。

      因此,请根据以下内容更改您的查询:

      select vc.cname, count(*) as catcount
      from video_categories vc, video_recordings vr
      where vc.id = vr.category
      group by vc.id
      ;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-13
        • 1970-01-01
        • 2018-09-03
        相关资源
        最近更新 更多