mysql 分組排序 取第N條全部記錄 同時存在條件篩選
阿新 • • 發佈:2019-02-12
1.首先利用條件篩選出基本資料
SELECT * from test where columna = 'xxx' AND columnb = 'xxx' and ......
2.對基本資料分組並利用SUBSTRING_INDEX和GROUP_CONCAT函式取出需要的欄位
SELECT tab1.columnc, tab1.columnd, tab1.columne,SUBSTRING_INDEX(GROUP_CONCAT(distinct tab1.[需要合併的欄位] ORDER BY tab1.[需要排序的欄位] DESC), ',', '1') month from (
SELECT * from test where columna = 'xxx' AND columnb = 'xxx') tab1 GROUP BY tab1.columne
說明: group_concat函式用來分組合並欄位,比如說按照ID分組,將name合併,具體用法問度娘吧。。。。
substring_index()函式可以取到某個字串中按照給定字元分割後的第N個字元,相當於現將字串按照某個字元分割成資料,然後去到陣列的第N個元素
3.然後通過連線取到其他欄位資料
SELECT tab2.* from test tab2 RIGHT JOIN ( SELECT tab1.columnc, tab1.columnd, tab1.columne,SUBSTRING_INDEX(GROUP_CONCAT(distinct tab1.[需要合併的欄位] ORDER BY tab1.[需要排序的欄位] DESC), ',', '1') month from ( SELECT * from test where columna = 'xxx' AND columnb = 'xxx' tab1 GROUP BY tab1.columne) tab3 on tab2.columnc = tab3.columnc and tab2.columnd = tab3.columne and tab2.columnf = tab3.columnf;
4.大功告成。綜合之後的SQL:
SELECT tab2.* from test tab2 RIGHT JOIN ( SELECT tab1.a, tab1.b, tab1.c,SUBSTRING_INDEX(GROUP_CONCAT(distinct tab1.d ORDER BY tab1.create_date DESC), ',', '1') d from ( SELECT * from test where a= 'XXXX' AND b= 'xxxx') tab1 GROUP BY tab1.c) tab3 on tab2.a= tab3.a and tab2.b= tab3.b and tab2.c= tab3.c and tab2.d = tab3.d;