Mariadb

首先按重要性排序,然後按部分分組

  • March 25, 2019

在此表方案中http://sqlfiddle.com/#!9/101a9c/9/0

id  section     rev     importance
2   1           b       6
1   1           a       5
3   2           c       9
5   3           e       6
4   3           d       5

我想order by **importance**那時group by **section**

所以我嘗試使用GROUP BY docs.section

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.section    ---GROUPING
ORDER BY docs.section, importance DESC

但得到了這個結果:

id  section     rev     importance
1   1           a       5
3   2           c       9
4   3           d       5

但我想要的結果應該是

id  section     rev     importance
2   1           b       6
3   2           c       9
5   3           e       6

我用了這個查詢

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

我首先將子查詢作為臨時表進行了排序,然後按重要性對其進行排序,然後按部分對外部查詢進行分組以獲得最終結果。

我相信你不能做你認為你想做的事。

讓我這樣說吧:如果您想“先按重要性排序,然後按部分分組”,請告訴我您打算如何對行進行分組,以便section = 1當一行有importance = 5而另一行有時importance = 6

你看到問題了嗎?這沒有道理。我怎樣才能importance = 6先訂購所有的東西,然後以某種方式按您因訂購而分開的行分組(即 where section = 1)?

這可能就是為什麼 SQL 語法group by首先需要您的子句,然後是您的order by子句 - 因為首先發生分組,然後發生排序。

有趣的是,您注意到您嘗試了以下 SQL:

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.section    ---GROUPING
ORDER BY docs.section, importance DESC

…但是當我將其粘貼到您的 Fiddle 中並執行時,出現錯誤:

Unknown column 'GROUPING' in 'group statement'

也許檢查一下你是如何得到你給出的結果的?

引用自:https://dba.stackexchange.com/questions/232958