带有日期比较的mysql查询

时间:2014-07-01 07:40:38

标签: mysql sql date select

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

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';

4 个答案:

答案 0 :(得分:0)

如果invoicedate数据类型是日期时间,则需要进行一次更正,即使用正确的括号表示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';

答案 1 :(得分:0)

变化:

 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')

答案 2 :(得分:0)

第一个问题是你没有必要的括号,即你的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';

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

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

如果是第二种情况,我会建议你制作该字段的日期或日期时间。

答案 3 :(得分:0)

试试这个:

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');