MySQL Query未选择正确的日期范围

时间:2012-05-18 12:21:38

标签: mysql date

我目前正在尝试运行SQL查询以在某个日期之间导出数据,但它运行查询正常,而不是日期选择,我无法弄清楚出了什么问题。

SELECT 
    title AS Order_No, 
    FROM_UNIXTIME(entry_date, '%d-%m-%Y') AS Date, 
    status AS Status,
    field_id_59 AS Transaction_ID,  
    field_id_32 AS Customer_Name, 
    field_id_26 AS Sub_Total, 
    field_id_28 AS VAT, 
    field_id_31 AS Discount, 
    field_id_27 AS Shipping_Cost, 
    (field_id_26+field_id_28+field_id_27-field_id_31) AS Total 
FROM 
    exp_channel_data AS d NATURAL JOIN
    exp_channel_titles AS t
WHERE 
    t.channel_id = 5 AND FROM_UNIXTIME(entry_date, '%d-%m-%Y') BETWEEN '01-05-2012' AND '31-05-2012' AND status = 'Shipped'  
ORDER BY 
    entry_date DESC

2 个答案:

答案 0 :(得分:6)

正如the manual中所述,日期文字应为YYYY-MM-DD格式。另外,请记住@ypercube在his answer中提出的观点,你想要:

WHERE t.channel_id = 5
  AND entry_date >= UNIX_TIMESTAMP('2012-05-01')
  AND entry_date <  UNIX_TIMESTAMP('2012-06-01')
  AND status = 'Shipped'

答案 1 :(得分:3)

除日期格式外还有另一个问题。要有效使用entry_date上的任何索引,在WHEREGROUP BYHAVING子句中使用条件时,不应将函数应用于该列(您可以使用格式在SELECT列表中,如果需要不同于要显示的默认格式)。编写查询部分的有效方法是:

 (  entry_date >= '2012-05-01'  
AND entry_date < '2012-06-01' 
 )

适用于DATEDATETIMETIMESTAMP列。