查询 MySQL 中 JSON 列中 JSON 项目日期之前的记录

Querying records before a date from a JSON item's date in a JSON column in MySQL

我正在从 MySQL 数据库中的 JSON 字段进行查询,到目前为止它似乎工作正常。它给了我记录。但我的问题是我不能 select JSON 字符串中的项目日期在特定日期之前。它似乎在给定日期之前和之后给我记录,这显然不起作用。这是我到目前为止的代码:-

select 
user_id, 
json_extract(user_profile, "$.gender") as gender, 
json_extract(user_profile, "$.dateofbirth") as dateofbirth
from user_profiles 
where json_extract(user_profile, "$.gender") = "Female" 
and json_extract(user_profile, "$.dateofbirth") < "06/15/1988"

我考虑过使用 我考虑过使用 DATE_FORMAT() 例如:-

where json_extract(user_profile, "$.gender") = "Female"
date_format(json_extract(user_profile, "$.dateofbirth"), "%d/%m/%Y") < "06/15/1988"

但是那只会让我没有记录。 有什么方法可以做到这一点 MySQL 可以从我正在查询的 JSON 字符串中理解日期格式?

假设 json 文档中的日期以 dd/mm/yyyy 格式存储,那么您需要:

where 
    json_unquote(user_profile->"$.gender") = 'Female'
    and str_to_date(json_unquote(user_profile->"$.dateofbirth"), '%d/%m/%Y') < '1988-06-15'

或者:

where 
    json_unquote(user_profile->"$.gender") = 'Female'
    and str_to_date(user_profile->"$.dateofbirth", '"%d/%m/%Y"') < '1988-06-15'

str_to_date() 将格式化字符串转换为 date,然后您可以将其与固定日期进行比较。

注意:MySQL 理解 -> 符号,可以用作 json_extract() 的快捷方式。

从专线小巴的回答来看,这似乎更有意义。非常感谢。 我仍然没有收到任何记录,但我设法通过从以下 Whosebug post 添加 json_unquote() 提供的 GMB 使其工作:

SQL 现在看起来像这样:-

select 
user_id, 
json_unquote(user_profile->'$.gender') as gender, 
json_unquote(user_profile->'$.dateofbirth') as dateofbirth
from tipanel.user_profiles
where 
user_profile->"$.gender" = 'Female'
and str_to_date(json_unquote(user_profile->'$.dateofbirth'), "%d/%m/%Y") < '1988-06-15';

如果可以做得更好,欢迎提出意见。