具有自訂順序的GROUP_CONCAT 函數
要從多行擷取資料並將它們合併為具有指定順序的單一串聯字串,GROUP_CONCAT可以利用功能。考慮下表:
+-----------+-------+------------+ | client_id | views | percentage | +-----------+-------+------------+ | 1 | 6 | 20 | | 1 | 4 | 55 | | 1 | 9 | 56 | | 1 | 2 | 67 | | 1 | 7 | 80 | | 1 | 5 | 66 | | 1 | 3 | 33 | | 1 | 8 | 34 | | 1 | 1 | 52 |
使用 GROUP_CONCAT函數:
SELECT li.client_id, group_concat(li.views) AS views, group_concat(li.percentage) FROM li GROUP BY client_id;
將傳回以下結果:
+-----------+-------------------+-----------------------------+ | client_id | views | group_concat(li.percentage) | +-----------+-------------------+-----------------------------+ | 1 | 6,4,9,2,7,5,3,8,1 | 20,55,56,67,80,66,33,34,52 | +-----------+-------------------+-----------------------------+
依升序對串聯視圖進行排序順序,可以將查詢修改如下:
SELECT li.client_id, group_concat(li.views ORDER BY li.views ASC) AS views, group_concat(li.percentage ORDER BY li.views ASC) AS percentage FROM li GROUP BY client_id
這將返回所需的結果:
+-----------+-------------------+----------------------------+ | client_id | views | percentage | +-----------+-------------------+----------------------------+ | 1 | 1,2,3,4,5,6,7,8,9 | 52,67,33,55,66,20,80,34,56 | +-----------+-------------------+----------------------------+
以上是如何使用GROUP_CONCAT以特定順序連接資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!