mysql - 热门报告指标 MYSQL

标签 mysql database join average

首先要祝贺这样一个伟大的网站,它总是以最专业的答案出现在搜索中。

我正在使用 MySql JOINS 并实际上尝试在 MySql 上应用一些预处理,让我们进入正题:

鉴于这 3 个表:

CREATE TABLE `reports_indicators` (
  `report_id` int(11) NOT NULL,
  `indicator_id` int(11) NOT NULL,
  `reported` varchar(10) DEFAULT NULL,
  `id` int(11) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`,`report_id`,`indicator_id`),
  KEY `fk_reports_has_indicators_indicators1` (`indicator_id`),
  KEY `fk_reports_has_indicators_reports1` (`report_id`)
) ENGINE=InnoDB AUTO_INCREMENT=77409 DEFAULT CHARSET=latin1;

CREATE TABLE `reports` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(255) DEFAULT 'untiteled'
) ENGINE=InnoDB AUTO_INCREMENT=11609 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

CREATE TABLE `indicators` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) DEFAULT NULL,
  `description` text,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=312 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

我正在尝试获得报告最多的指标,就这么简单......但我做不到!

我所能得到的只是来自一份报告的一组指标:

  SELECT *
  FROM reports_indicators as ri
  INNER JOIN indicators as i
  ON i.id = ri.indicator_id
  WHERE ri.report_id=6867
  ORDER BY ri.report_id asc;

我知道还差得远,但当我开始尝试 AVG 时发现无法将其放在赖特位置。

有什么帮助吗?

非常感谢!

bto.

最佳答案

这假设“报告最多的指标”是指在 reports_indicators 表中具有最多相关记录的指标将排在最前面:

SELECT 
    i.id,
    i.name, 
    COUNT(*) AS TotalReported
FROM 
    reports_indicators as ri
    INNER JOIN indicators as i
        ON i.id = ri.indicator_id
GROUP BY i.id, i.name
ORDER BY COUNT(*) DESC;

关于mysql - 热门报告指标 MYSQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12431317/

相关文章:

php - MySQL内连接输出到php中的html表

MYSQL 线程限制

c# - 如何在同一行中找到重复的名称/值?可以算吗?

ruby - 检查 30M 行文本文件中特定项目是否存在的最快方法

database - AWS RDS 备份

sql-server - Join 会减慢 sql

mysql 显示公司的所有其他结果

mysql - 执行插入查询而不插入任何行?

php - 检查某行某列某个字段是否为空

android - 与不是主键的列建立关系