繁体   English   中英

MySQL查询与日期比较

[英]mysql query with date comparison

我已使用以下查询获取大于2012的信息,但与日期相比我没有得到正确的数据,请给我正确的查询? MYSQL查询:

SELECT a.invoiceno,
       a.invoicerefno,
       a.invoicedate,
       c.companyname,
       a.grandtotal,
       a.twempname,
       itemdescription,
       quantity
FROM twsql_twalldata.t_invoicedet a
INNER JOIN twsql_twalldata.t_salesinv_items b ON a.invoiceno=b.invoiceno
INNER JOIN twsql_twalldata.t_customerdet c ON a.customercode=c.customercode
WHERE a.twempname NOT LIKE '%Auto%'
  AND itemdescription LIKE '%AMC%'
  OR itemdescription LIKE '%annual maintenance contract%'
  AND invoicecancelled=0
  AND a.invoicedate > '2012-04-01 00:00:00';

如果invoicedate日期数据类型为datetime,则需要进行一项更正,即对OR条件使用正确的括号。

WHERE 
a.twempname NOT LIKE '%Auto%'
AND ( itemdescription LIKE '%AMC%' OR itemdescription LIKE '%annual maintenance contract%')
AND invoicecancelled=0
AND a.invoicedate > '2012-04-01 00:00:00';

更改:

 AND a.invoicedate > '2012-04-01 00:00:00';

至:

 AND a.invoicedate >  STR_TO_DATE('2012-04-01 00:00:00','%Y-%m-%d' %h:%i:%s')

第一个问题是您没有必需的括号,即您的OR条件应放在方括号内。

SELECT a.invoiceno,
       a.invoicerefno,
       a.invoicedate,
       c.companyname,
       a.grandtotal,
       a.twempname,
       itemdescription,
       quantity
FROM twsql_twalldata.t_invoicedet a
INNER JOIN twsql_twalldata.t_salesinv_items b ON a.invoiceno=b.invoiceno
INNER JOIN twsql_twalldata.t_customerdet c ON a.customercode=c.customercode
WHERE a.twempname NOT LIKE '%Auto%'
  AND (itemdescription LIKE '%AMC%' OR itemdescription LIKE '%annual maintenance contract%')
  AND invoicecancelled=0
  AND a.invoicedate > '2012-04-01';

第二个问题可能是您的发票date不是datedatetime date类型,那么您需要先将其转换为date ,然后进行比较

AND STR_TO_DATE(a.invoicedate, '%Y-%m-%d') > '2012-04-01';

如果是第二种情况,我建议您指定该字段的日期或日期时间。

尝试这个:

SELECT a.invoiceno,
       a.invoicerefno,
       a.invoicedate,
       c.companyname,
       a.grandtotal,
       a.twempname,
       itemdescription,
       quantity
FROM twsql_twalldata.t_invoicedet a
INNER JOIN twsql_twalldata.t_salesinv_items b ON a.invoiceno=b.invoiceno
INNER JOIN twsql_twalldata.t_customerdet c ON a.customercode=c.customercode
WHERE a.twempname NOT LIKE '%Auto%' AND 
      (itemdescription LIKE '%AMC%' OR itemdescription LIKE '%annual maintenance contract%') AND 
       invoicecancelled=0 AND DATE(a.invoicedate) > DATE('2012-04-01');

暂无
暂无

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

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