简体   繁体   English

SQL-存储在JSON varchar中的SELECT WHERE日期大于或小于固定日期

[英]SQL - SELECT WHERE date stored in a JSON varchar is greater or less than a fixed date

I have a VARCHAR column where user store custom data from Input, Select, Checkbox and Input type date. 我有一个VARCHAR列,用户可以在其中存储来自输入,选择,复选框和输入类型日期的自定义数据。

[{"i":24,"v":[0,1,4]},{"i":26,"v":[2,3,6,10]},{"i":41,"v":"2019-03-18"},{"i":27,"v":[26]},{"i":6,"v":"Very happy to be here."},{"i":13,"v":4},{"i":22,"v":9},{"i":3,"v":"Numerous"},{"i":4,"v":3},{"i":29,"v":[2,3]},{"i":30,"v":[3,4]}]

I know ID 41 is a date. 我知道ID 41是日期。 I want to SELECT this user if ID 41 exists and if the data is greater than a fixed date. 如果ID 41存在并且数据大于固定日期,我想选择此用户。

My idea is to use REGEXP to test if ID 41 exists : REGEXP \\'(\\{"i":41,) and then to catch the date and test it (TO_DATE ?). 我的想法是使用REGEXP测试ID 41是否存在: REGEXP \\'(\\{"i":41,) ,然后捕获日期并对其进行测试(TO_DATE?)。 How can I do this second part ? 我该如何做第二部分?

Edit - I have found a solution to catch the date with REGEXP_SUBSTR : 编辑-我找到了一种解决方案,以使用REGEXP_SUBSTR捕获日期:

SELECT user_id, REGEXP_SUBSTR(my_json_col, \'(?<=\{"i":41,"v":")(.*?)(?="\})\') AS dt FROM ...

=> dt : 2019-03-18 => DT:2019-03-18

I still cannot test the value. 我仍然无法测试该值。

You should extract the data in separate columns at insert time, for performance reasons. 出于性能原因,应在插入时将数据提取到单独的列中。 The way you want to do it is VERY slow. 您想要做的方式非常慢。

However, if you MUST do it that way, check this out: How can write queries in MySQL that can parse JSON data in a column? 但是,如果必须这样做,请检查以下内容: 如何在MySQL中编写可解析列中JSON数据的查询?

It shows you how to address the data directly, not with regular expressions. 它显示了如何直接处理数据,而不是使用正则表达式。 AFAIK this works for MySQL/Postgres, most RDBMS have JSON capabilities but I don't think it is very standardized, so check out the appropriate dox. AFAIK适用于MySQL / Postgres,大多数RDBMS具有JSON功能,但我认为它不是非常标准化的,因此请查看适当的dox。

I think JSON_EXTRACT(column,'$[41].v') is what you are after, check https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html for more insight. 我认为您JSON_EXTRACT(column,'$[41].v') ,请查看https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html以获取更多信息。

Solution with REGEXP_SUBSTR and HAVING : REGEXP_SUBSTRHAVING的解决方案:

SELECT
    user_id,
    REGEXP_SUBSTR(my_json_col, \'(?<=\{"i":41,"v":")(.*?)(?="\})\') AS dt
FROM mytable
HAVING
    DATE(dt) < DATE(NOW())
    and DATE(dt) > DATE("2019-03-15")
    and dt <> ""

It works well. 它运作良好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM