SQL 查询 Between with or

SQL Query Between with or

好吧,我在 mysql 中有一个 table,我想获取某个日期范围内的数据,但是当执行此查询时:

select * from cartap c inner join rastreo r on (c.idCartaporte=r.idcartap) 
inner join contratistas ct on (ct.NoContrato=c.NumeroContrato) inner join datosfiscales df 
on (ct.DatosFiscales_ClaveUnicaDF=df.ClaveUnicaDF) where creationdate between '$begdate' 
and '$enddate' and idper ='2001' or idper ='2002' and 
estadopago like '%$estadocp%' and estadoliquidacion like '%$estadoliq%' order by $order

我得到的数据超出了那个范围,我知道是因为 OR 条件,因为它给了我正确的 idper 值,但是 return 日期的值超出了范围,我需要使用那个或其他东西类似,因为我想得到的是两个日期之间的报告,并为两个(或更多)客户(即 idper)应用过滤器,但在这些日期之间

您似乎不了解布尔条件的规则。因此,我通常建议您在条件混合 ands 和 ors 时始终使用括号。它们就像辅助轮。

但是,对于您的情况,in 解决了问题:

where creationdate between '$begdate' and '$enddate' and
      idper in ('2001', '2002') and 
      estadopago like '%$estadocp%' and 
      estadoliquidacion like '%$estadoliq%'

并且您应该学会使用参数,这样您的代码就不会出现意外的语法错误和 SQL 注入。