从JSON类型的数据提取时,有什么方法可以比较小时?
目前,我有此查询:
SELECT * FROM
(SELECT clinics.id as cid, clinics.lat, clinics.lng, clinics.opening_hours,
clinics.logo, clinics.address, clinics.city, clinics.state, clinics.name, clinics.description,
clinics.zip, clinics.phone_number, clinics.email, clinics.url, clinics.bookmark_url,
clinics.marker, timezone,
countries.full_name AS country,
(6378 * acos(
cos(radians(-33.8688197)) * cos(radians(lat)) *
cos(radians(lng) - radians(151.2092955)) +
sin(radians(-33.8688197)) * sin(radians(lat))))
AS distance
FROM clinics
JOIN countries ON countries.id = clinics.country_id
LEFT JOIN clinics_services ON clinics.id = clinics_services.clinic_id
WHERE CAST(JSON_EXTRACT(`opening_hours`, '$."wednesday-to"') as time) > CAST('09:00' as time)
GROUP BY clinics.id
) AS distances
WHERE distance < 5
ORDER BY distance ASC
如果运行此查询,我将得到正确的结果:
SELECT JSON_EXTRACT(`opening_hours`, '$."wednesday-to"') FROM clinics
(结果):
"17:30"
"19:00"
"12:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"19:00"
"18:00"
"19:00"
"18:00"
"18:00"
"18:00"
"18:00"
"18:00"
"19:00"
但是,如果我尝试将其强制转换为时间(使用此查询),则会得到NULL:
SELECT CAST(JSON_EXTRACT(`opening_hours`, '$."wednesday-to"') as TIME) FROM clinics
我究竟做错了什么?
最佳答案
看来@BillKarwin是正确的。您需要用JSON_EXTRACT
包装JSON_UNIQUOTE
。
Chaining JSON_EXTRACT with CAST or STR_TO_DATE fails
https://www.db-fiddle.com/f/nomb47TQ2Rxaw5MGc1WtSs/0
SELECT CAST(JSON_UNQUOTE(JSON_EXTRACT('{"hour":"10:00"}','$.hour')) as time) > CAST('09:00' as time);
在您的情况下:
...
WHERE CAST(JSON_UNQUOTE(JSON_EXTRACT(`opening_hours`, '$."wednesday-to"')) as time) > CAST('09:00' as time)
...