mysql - 从 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 字符串中理解日期格式?
解决方案
假设 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()
.
推荐阅读
- javascript - 是否像这样的好习惯在多个文件中实现 javascript 类?
- java - 如何从 ArrayList<> 获取数组
- c++ - 不可能在函数定义的类外声明器中完全限定类名
- javascript - 如何更改 connect 方法中的某些部分代码(将使用 mapStateToProps)以及此处存在的动作移动到 index.js(动作)?
- sql-server - 执行 STUFF 返回查询字符串而不存储到变量中
- angular - Angular + Material Table - 如果我使用 un Pipe 过滤器,如何拖放行
- python - 检查目标时出错:预期 dense_9 的形状为 (1,) 但得到的数组的形状为 (20,)
- date - vscode在每个新行中插入日期时间?
- javascript - 尝试使用 rest api 创建 Hpalm 缺陷时出现“415 Unsupported Media Type”
- visual-studio-code - Visual Studio 代码用户片段大写不能正常工作