我正在从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()
将格式化的字符串转换为date
,然后可以将其与固定日期进行比较。
注意:MySQL理解->
表示法,可以将其用作json_extract()
的快捷方式。
从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';
如果可以做得更好,欢迎发表评论。