【问题标题】:Querying records before a date from a JSON item's date in a JSON column in MySQL从 MySQL 中的 JSON 列中的 JSON 项目的日期查询日期之前的记录
【发布时间】:2020-04-25 23:52:58
【问题描述】:

我正在从 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 字符串中理解日期格式?

【问题讨论】:

  • 可能是个愚蠢的问题数据库中 dateofbirth 列中的日期是什么格式
  • 格式为dd/mm/yyyy

标签: mysql json date-formatting json-extract


【解决方案1】:

假设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 理解 -&gt; 表示法,可以使用 json_extract() 的快捷方式。

【讨论】:

  • 谢谢。这真的很有帮助。我没有得到任何结果,但我将 json_unquote() 添加到您的查询中,它对我有用。非常感谢您的反馈
  • @JamLizzy101:是的,你是对的......我们需要json_unquote() 删除 JSON 提取返回的字符串周围的引号。我相应地编辑了我的答案。
【解决方案2】:

从 GMB 的回答看来,这似乎更有意义。非常感谢。 我仍然没有得到任何记录,但我设法通过从以下 Stackoverflow 帖子中添加 json_unquote() 提供的 GMB 使其工作:Chaining JSON_EXTRACT with CAST or STR_TO_DATE fails

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';

如果可以做得更好,欢迎评论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-22
    相关资源
    最近更新 更多