Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

mysql - Sort by JSON field values

I have a table with json values like this:

-Table 1

id    |   name   |   data
------+----------+---------------
1     | Test     | {"city_id": 3, "email":"[email protected]", "city_name":"something"}
2     | Test 2   | {"city_id": 1, "email":"[email protected]", "city_name":"another"}
3     | Test 3   | {"city_id": 6, "email":"[email protected]", "city_name":"blahblah"}

Now I want SELECT records with order by data.city_name, so I use this code:

SELECT id, name, JSON_EXTRACT(data, 'city_name') AS cityName
FROM table1
ORDER BY cityName ASC

but this query cannot sort my records correctly !

P.S: city_name have UTF-8 characters.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

you do not seem to be using JSON_EXTRACT() properly, try with:

SELECT id, name, JSON_EXTRACT(data, '$.city_name') AS cityName 
FROM demo ORDER BY cityName ASC

Demo Fiddle


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...