可以重建此查询以使其更优化吗?

时间:2019-03-25 09:30:26

标签: mysql mariadb greatest-n-per-group query-performance

sqlfiddle:http://sqlfiddle.com/#!9/a209c7/2/0

我的桌子是:

-- borrowed from https://stackoverflow.com/questions/55325155

CREATE TABLE IF NOT EXISTS `docs` (
  `id` int(6) unsigned NOT NULL,
  `section` int(2) unsigned NOT NULL,
  `rev` varchar(3) NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `docs` (`id`, `section`, `rev`) VALUES
  ('1', '1', 'a'),
  ('2', '1', 'b'),
  ('3', '2', 'c'),
  ('4', '3', 'd'),
  ('5', '3', 'e');

CREATE TABLE IF NOT EXISTS `docs_importance` (
  `doc_id` int(6) unsigned NOT NULL,
  `importance` int(3) unsigned NOT NULL
) DEFAULT CHARSET=utf8;
INSERT INTO `docs_importance` (`doc_id`, `importance`) VALUES
  ('1', '1'),
  ('1', '2'),
  ('1', '2'),
  ('2', '2'),
  ('2', '4'),
  ('3', '9'),
  ('4', '5'),
  ('5', '6');

我的查询是:

-- based on answer https://stackoverflow.com/questions/55325155

SELECT t.id, t.section, t.rev, t.importance 
FROM (SELECT docs.id, docs.section, docs.rev, (SELECT SUM(docs_importance.importance) 
                                               FROM docs_importance 
                                               WHERE docs_importance.doc_id = docs.id) AS importance
      FROM docs
      GROUP BY docs.id
      ORDER BY importance DESC
      ) AS t
GROUP BY t.section;

我正在做的是按重要性的计算得出的 sum docs 行进行排序,然后按部分对其进行分组以获得仅针对每个部分的重要性最高的文档

能否以更好的方式和更快的速度重现此查询?

0 个答案:

没有答案