dougui4325 2015-03-24 21:15
浏览 25
已采纳

MySQL:计算每个字段中的不同值

I am not sure if there is no answer here on Stack Overflow, but I did not find exact thing there. So, I have a table with data like this:

id    | sector | type  | level
      |        |       |
1     | TMT    | Long  | First
2     | Energy | Long  | Second
3     | TMT    | Short | Third
4     | Other  | Long  | First
5     | TMT    | N/A   | Sixth
6     | Other  | Short | First

What I need is summary of each different value in each field, like this:

Sector TMT: 3
Sector Energy: 1
Sector Other: 2
Type Long: 3
Type Short: 2
Type N/A: 1
Level First: 3
Level Second: 1
Level Third: 1
Level Sixth: 1

Type and Level have fixed values. Sectors could be dynamic, I mean there is no final list as they are adding with each item.

For now I am selecting all rows and processing it with PHP:

SELECT `sector`, `type`, `level` FROM `table`;

and for example:

<?php
$result['type_long'] = 0;
$result['type_short'] = 0;
$result['type_na'] = 0;
foreach ($rows as $row)
{
    if ($row['type'] == 'Long')
    {
        $result['type_long']++;
    }
    else if ($row['type'] == 'Short')
    {
        $result['type_short']++;
    }
    else if ($row['type'] == 'N/A')
    {
        $result['type_na']++;
    }
}

etc. For 10000 records it's not really fast cause I need to select all rows from database and then do something to them via PHP.

Is there any way I can do this faster with MySQL?

Thanks!

  • 写回答

1条回答 默认 最新

  • doufeinai6081 2015-03-24 21:27
    关注

    This is a straightforward application of the union of several summary queries. A typical summary query would be

    SELECT Sector, COUNT(*) cnt
      FROM mytable
     GROUP BY Sector
    

    To get your exact result set you could do something like this:

    SELECT CONCAT('Sector ', Sector, ':') item, COUNT(*) cnt FROM mytable GROUP BY Sector
    UNION ALL
    SELECT CONCAT('Type ', Type, ':') item, COUNT(*) cnt FROM mytable GROUP BY Type
    UNION ALL
    SELECT CONCAT('Level', Level, ':') item, COUNT(*) cnt FROM mytable GROUP BY Level
    

    If you want this to be optimally fast, you might try adding indexes on the three columns.

    MySQL is quite good at handling summary queries with high performance. Even with multiple separate SELECT queries in this UNION, it will perform an order of magnitude better than transferring all your raw data rows from the server to your MySQL program.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)