简体   繁体   English

从日期时间字段中选择年份以及月份,然后插入日期字段

[英]Select Year as well as Month from Datetime field and Insert into Date field

I have value in field 'DateandTime' as 2015-05-12 12:04:15 and it is stored table1. 我在字段“ DateandTime”中具有2015-05-12 12:04:15的值,并将其存储在table1中。 I have so many values in same month. 我在同一个月有很多价值观。

I just want to insert it to table2 only year and month in the format '2015-05' and the field type is date and the field name is 'Date'. 我只想将其插入到仅年份和月份的table2中,格式为'2015-05',字段类型为date,字段名称为'Date'。

How can I do this in mysql? 我该如何在mysql中做到这一点? And not in PHP. 而不是在PHP中。

Kindly suggest me. 请建议我。

Try this (edited, see below): 尝试以下操作(编辑,请参见下文):

-- This query fails
-- insert into table2 values (select distinct(DATE_FORMAT(DateandTime, "%Y-%m")) as yearmonth from table1)

UPDATE: 更新:

Yes, you're right. 你是对的。 I write the answer without executing it... Try this, please: 我没有执行就写出答案...请尝试以下操作:

insert into table2 select distinct(STR_TO_DATE(DATE_FORMAT(DateandTime, "%Y-%m"), '%Y-%m')) from table1

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

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