我有一個包含項目的表格,其中一些是其他項目的子項目(我會說很像某種論壇會話,有些是以前的子項目,有些沒有子項目,有的有很多孩子,但只有一個層次深度,有沒有孩子的孩子),例如我得到下面的列表中有一些標準的,由ID的排序查詢後:在mysql中分組和排序結果(具有分層信息的數據)
| id | title | date | childof |
| 002 | tit2 | 2017-02-23 | 000 | if 000, not a child
| 003 | tit3 | 2017-05-12 | 000 | not a child
| 004 | tit4 | 2017-03-25 | 002 | child of 002
| 005 | tit5 | 2017-03-26 | 002 | other child of 002
| 006 | tit6 | 2017-06-13 | 000 | not a child
| 007 | tit7 | 2017-07-06 | 003 | only child of 003
我的問題是有關排序/分組結果:我想要得到的結果如下:
| id | title | date | childof |
| 006 | tit6 | 2017-06-13 | 000 | no child most recent at first level
| 003 | tit3 | 2017-05-12 | 000 | one child
| 007 | tit7 | 2017-07-06 | 003 | only child of previous
| 002 | tit2 | 2017-02-23 | 000 | two children
| 004 | tit4 | 2017-03-25 | 002 | child #1 of 002 oldest
| 005 | tit5 | 2017-03-26 | 002 | child #2 of 002 most recent
- 按日期(第一次最近)爲第一級其父不論其日後被重組,但與最早的命令
- 孩子先下父
我的出發(即兒都沒有的項目)點類似於:
SELECT * FROM mytable WHERE somecriteriaok ORDER BY日期GROUP BY childof。
當然,我嘗試了更復雜的解決方案,但似乎無法實現上述結果,所以我試圖想出這個問題,試圖使它簡單明瞭......希望我成功了,並會得到一些提示,去(原諒我的英語......)。
Pierre。
Waou。正確地釘牢!不知道COALESCE ...所以使用GROUP BY不是解決方案,感謝您的快速回答,我已經將它放在了我的複雜請求中,並且它可以工作! – pierr0t