sql="select data1 From test where data2='123' AND data3 IN ('No','2001','2002','2003','2004','2005','2006','2007','2008','2009')"
原本以上這樣寫輸出的排序沒問題...
更改後加上 GROUP_CONCAT & GROUP BY
sql="select GROUP_CONCAT(data1) From test where data2='123' AND data3 IN ('No','2001','2002','2003','2004','2005','2006','2007','2008','2009')GROUP BY YY"
後第一筆資料排序就出錯了
變成 2009,2008,2007,2006,2004,2003,2002,2001,NO 這樣
其他筆資料也都跑錯位了
不知道是不是語法寫錯? 還是我不了解語法執行順序?
-- group_concat : case 1
select name,group_concat(data order by data SEPARATOR ',' ) as combdata
from test
group by name
order by name
-- group_concat : case 2
select name,group_concat(data order by data SEPARATOR ',' ) as combdata
from test
group by name
order by name desc
-- group_concat : case 3
select name,group_concat(data order by data desc SEPARATOR ',' ) as combdata
from test
group by name
order by name
-- group_concat : case 4
select name,group_concat(data order by data desc SEPARATOR ',' ) as combdata
from test
group by name
order by name desc
-- group_concat : case 5
select name,group_concat(data SEPARATOR ',' ) as combdata
from test
group by name
Demo 看看差異在哪,
就知要不要排序了
我給他分號資料會變成 data-01 data-01 並無法順利產出資料
select name,group_concat('data-01' order by data SEPARATOR ',' ) as combdata
from test
group by name
order by name desc
非常感謝你!
select name,group_concat('data-01' order by data SEPARATOR ',' ) as combdata
from test
group by name
order by name desc
非常感謝你!
select name,group_concat(`data-01` order by `data-01` SEPARATOR ',' ) as combdata
from test
group by name
order by name desc
data-01 左右邊的 ` 用鍵盤左邊的 Tab 按鍵上方那個鍵
data-01 建議改成 data_01 以免之後下 SQL 時出現不可預期的錯誤,
還要再花時間除錯
select name,group_concat(`data-01` order by `data-01` SEPARATOR ',' ) as combdata
from test
group by name
order by name desc
[Demo](https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=8a23c45830853c497cffca511b718255)
data-01 左右邊的 ` 用鍵盤左邊的 Tab 按鍵上方那個鍵
data-01 建議改成 data_01 以免之後下 SQL 時出現不可預期的錯誤,
還要再花時間除錯
試試看這樣.
sql="select GROUP_CONCAT(data1) FROM (
SELECT data1 From test where data2='123' AND data3 IN ('No','2001','2002','2003','2004','2005','2006','2007','2008','2009') ORDER BY XXX) AS a
GROUP BY YY"
sql="select GROUP_CONCAT(data1) FROM (
SELECT data1 From test where data2='123' AND data3 IN ('No','2001','2002','2003','2004','2005','2006','2007','2008','2009') ORDER BY XXX) AS a
GROUP BY YY"
https://www.mysqltutorial.org/mysql-order-by/
When you use the SELECT statement to query data from a table, the result set is not sorted. It means that the rows in the result set can be in any order.
當你沒有下 order by 時, 查詢的結果會是 無序 的. 這是關聯式資料庫都這樣,不只MySQL.
所以我們通常會有一個 遞增 (或是遞減) 的欄位,或是有時間戳的欄位,以方便做 order by.