简体   繁体   English

MySQL在范围内的表中插入日期记录

[英]MySQL insert date records in a table within a range

I am wondering if there is a method to do this by strict SQL query. 我想知道是否有一种方法可以通过严格的SQL查询来执行此操作。

Suppose I want to INSERT a series of records into a MySQL table based on a range of dates, but with no corresponding "table" for the dates something like: 假设我要INSERT的一系列记录到基于日期范围的MySQL表,但没有相应的“表”的日期是这样的:

INSERT INTO scheduleable( available_date, status ) 
SELECT DATE, 'open' FROM DATES BETWEEN '2017-01-15' AND '2017-05-01'

Only, obviously, DATES is not a real table. 显然,仅DATES不是真正的表。

Is something like this possible? 这样的事情可能吗? The obvious benefit is being able to insert records that have the right day values for months like February and April. 明显的好处是能够插入月份值正确的记录,例如2月和4月。

I used the solution provided here - however, I chose to turn the query given into a VIEW - which is far superior to actually creating a physical table of dates! 我使用了此处提供的解决方案-但是,我选择将给定的查询转换为VIEW比实际创建物理日期表要好得多!

However, I was told by MySQL that you can't have a subquery in the 'FROM' clause , so my solution is not completely elegant, but perhaps the "10 list" could be useful for other applications. 但是,MySQL告诉我can't have a subquery in the 'FROM' clause ,因此我的解决方案并不完美,但是“ 10列表”可能对其他应用程序很有用。 Here's my solution: 这是我的解决方案:

First create this view: 首先创建此视图:

CREATE OR REPLACE VIEW `_v_list_10` AS 
SELECT 0 AS `a` union all select 1 AS `1` union all select 2 AS `2` union all select 3 AS `3` union all select 4 AS `4` 
union all select 5 AS `5` union all select 6 AS `6` union all select 7 AS `7` union all select 8 AS `8` union all select 9 AS `9`;

Then create this view: 然后创建此视图:

CREATE OR REPLACE VIEW _v_dates_1000 AS 
SELECT CURDATE() + INTERVAL 365 DAY - INTERVAL (a.a + (10 * b.a) + (100 * c.a)) DAY AS Date
FROM _v_list_10 AS a
CROSS JOIN _v_list_10 AS b
CROSS JOIN _v_list_10 AS c

NOTE that my date range starts 365 days in the future, and goes back a thousand from there. 请注意,我的日期范围从将来的365天开始,并从那里返回一千。 You could easily build it to 10,000 or 100,000 or etc. 您可以轻松地将其构建为10,000或100,000或更多。

As I have an information database that solely contains near-constant things like state and country names, US counties, etc., this was a good candidate for that database. 因为我有一个仅包含近乎恒定的信息(例如州和国家/地区名称,美国县等)的信息数据库,所以该数据库非常适合该候选人。 And, it takes NO SPACE. 而且,它不需要空间。 Hope this helps someone else out! 希望这可以帮助其他人!

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

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