按JSON字段值排序

时间:2017-07-17 07:03:52

标签: mysql json

我有一个像这样的json值的表:

- 表1

id    |   name   |   data
------+----------+---------------
1     | Test     | {"city_id": 3, "email":"test@test.com", "city_name":"something"}
2     | Test 2   | {"city_id": 1, "email":"test2@test2.com", "city_name":"another"}
3     | Test 3   | {"city_id": 6, "email":"test3@test3.com", "city_name":"blahblah"}

现在我需要SELECT order by的{​​{1}}条记录,因此我使用此代码:

data.city_name

但是此查询无法正确排序我的记录!

P.S:SELECT id, name, JSON_EXTRACT(data, 'city_name') AS cityName FROM table1 ORDER BY cityName ASC 有UTF-8字符。

3 个答案:

答案 0 :(得分:12)

您似乎没有正确使用JSON_EXTRACT(),请尝试:

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

Demo Fiddle

答案 1 :(得分:1)

检查这个。

SELECT Id ,name,SUBSTRING_INDEX(SUBSTRING_INDEX(data,'city_name":"',-1),'"',1) as CITY
FROM tempjson
order by SUBSTRING_INDEX(SUBSTRING_INDEX(data,'city_name":"',-1),'"',1)

OutPut:

enter image description here

答案 2 :(得分:1)

我通常cast将JSON值(->>)设置为正确的类型,以便正确排序:

SELECT id, name, data->>'$.city_name' AS cityName
FROM table1
ORDER BY CAST(cityName AS CHAR) ASC

否则,最终将以blob(二进制)的形式进行排序,它们被视为二进制字符串(字节字符串),因此它们具有二进制字符集和排序规则,并且比较和排序基于字节的数值列值(ref)。