MySQL在两个ISO格式的日期之间选择

时间:2018-08-03 13:05:08

标签: mysql date

我想选择mysql表中所有日期在给定日期之间的行。我数据库中的格式例如

"2018-09-28T12:00:00".

这是我的查询

SELECT d.field_datum_der_veranstaltung_value AS field_datum_der_veranstaltung_value, n.nid AS nid, n.title AS title
FROM 
{node} n
LEFT OUTER JOIN {field_data_field_datum_der_veranstaltung} d ON d.entity_id = n.nid
WHERE (d.field_datum_der_veranstaltung_value BETWEEN '2018-01-01T00:00:00' AND '2018-01-30T23:59:00') 
ORDER BY d.field_datum_der_veranstaltung_value ASC

请注意,这是Drupal API生成的查询,该查询正在运行(以防您怀疑{node}

现在,由于数据库中的日期是字符串,我如何比较这些值?

2 个答案:

答案 0 :(得分:0)

您可以尝试使用STR_TO_DATE函数获取DateTime

SELECT d.field_datum_der_veranstaltung_value AS field_datum_der_veranstaltung_value, n.nid AS nid, n.title AS title
FROM 
{node} n
LEFT OUTER JOIN {field_data_field_datum_der_veranstaltung} d ON d.entity_id = n.nid
WHERE (d.field_datum_der_veranstaltung_value
 BETWEEN STR_TO_DATE('2018-01-01T00:00:00', '%Y-%m-%d')  AND  STR_TO_DATE('2018-01-30T23:59:00', '%Y-%m-%d') ) 
ORDER BY d.field_datum_der_veranstaltung_value ASC

或者您可以使用CAST函数CAST(d.field_datum_der_veranstaltung_value AS DATETIME)设置日期时间。

SELECT d.field_datum_der_veranstaltung_value AS field_datum_der_veranstaltung_value, n.nid AS nid, n.title AS title
FROM 
{node} n
LEFT OUTER JOIN {field_data_field_datum_der_veranstaltung} d ON d.entity_id = n.nid
WHERE (CAST(d.field_datum_der_veranstaltung_value AS DATETIME)
 BETWEEN CAST('2018-01-01T00:00:00' AS DATETIME)  AND  CAST('2018-01-30T23:59:00' AS DATETIME)
ORDER BY d.field_datum_der_veranstaltung_value ASC

sqlfiddle

答案 1 :(得分:0)

这是iso DATE_FORMAT(date, '%Y-%m-%dT%TZ')的日期的示例,请尝试如下所示

SELECT * from table_name
FROM table_name 
where datecondition>=DATE_FORMAT('2018-01-01T00:00:00', '%Y-%m-%dT%TZ')
and datecondition <=DATE_FORMAT('2018-01-30T23:59:00', '%Y-%m-%dT%TZ')