首页 > 解决方案 > 从 MySQL 中的 JSON 列中的 JSON 项目的日期查询日期之前的记录

问题描述

我正在从 MySQL 数据库中的 JSON 字段进行查询,到目前为止似乎工作正常。它给了我记录。但我的问题是我无法选择 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 字符串中理解日期格式?

标签: mysqlsqljsondate-formattingjson-extract

解决方案


假设 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()将格式化的字符串转换为 a date,然后您可以将其与固定日期进行比较。

注意:MySQL 理解这种->表示法,它可以用作json_extract().


推荐阅读