我的sql查询在where子句的某些条件下获取所有行

时间:2014-08-26 04:13:24

标签: mysql

我的sql查询下面,

select SQL_CALC_FOUND_ROWS * from `MYDATABASE`.`MYTABLE` 
   WHERE (Date(timestamp) BETWEEN '1970-01-01' and '2014-08-25') 
      and (COLA='') and (COLB = '') and COLC = '1' 
        AND (LIKE CLAUSE ON ANOTHER 10 COLUMNS) desc Limit  0, 10 ;

现在对于ColA和COLB,我有时会填充值,有时它们会变为空字符串或Null值,所以每当我得到这些值时,我的查询都不返回任何行。我可以理解为什么我没有行,但是现在我的要求是每当我获得空值时获取所有行,或者为这些列中的任何一列获取空字符串。

我该怎么做?我尝试使用不是Null,但是这会破坏我的代码,因为当我将null值传递给COLA和COLB时可能会有效但是当COLA具有有效值并且COLB传递为null时,它仍然会在我希望它满足COLA条件时提供所有记录?对不起,我没有任何DBA,因为我现在戴着帽子。

实际查询如下所示

select SQL_CALC_FOUND_ROWS * from `MYDATABASE`.`MYTABLE` 
   WHERE (Date(timestamp) BETWEEN '1970-01-01' and '2014-08-25') 
      and (COLA='someparameter captured from UI,it could be null or empty string') and (COLB = 'someparameter captured from UI,it could be null or empty string') and COLC = '1' 
        AND (LIKE CLAUSE ON ANOTHER 10 COLUMNS) desc Limit  0, 10 ;


select SQL_CALC_FOUND_ROWS * from MYTABLE WHERE (Date(timestamp) BETWEEN '1970-01-01' and 'CURRENTDATE') and COLA = ('12001'OR'12002') and COLB = ('VAL1'OR 'VAL2' OR 'VAL3' OR 'VAL4'OR 'VAL5'OR 'VAL6') and COLC = '1' and (COLD LIKE '%%' OR COLE LIKE '%%' OR COLF LIKE '%%' OR COLG LIKE '%%'  OR COLH LIKE '%%' OR COLI LIKE '%%' OR COLM LIKE '%%' OR COLN LIKE '%%' OR COLP LIKE '%%')  order  by Date(timestamp) desc Limit  0, 100

2 个答案:

答案 0 :(得分:0)

试试这个

select SQL_CALC_FOUND_ROWS * from `MYDATABASE`.`MYTABLE` 
WHERE (Date(timestamp) BETWEEN '1970-01-01' and '2014-08-25') 
and (COLA IS NULL OR COLA = '') and (COLB IS NULL OR COLB = '') and COLC = '1' 
AND (LIKE CLAUSE ON ANOTHER 10 COLUMNS) desc Limit  0, 10 ;

答案 1 :(得分:0)

你应该知道'12001'OR'12002'是一个逻辑表达式,它在Mysql中返回一个布尔值(0-false/1-true)。

select ('12001'OR'12002'), 1=('12001'OR'12002'), '1'=('12001'OR'12002'), '0'=('12001'OR'12002')

('12001'OR'12002') | 1=('12001'OR'12002') | '1'=('12001'OR'12002') | '0'=('12001'OR'12002')|
-------------------|----------------------|------------------------|-----------------------|
                  1|                     1|                       1|                      0|

除非COLA = ('12001'OR'12002')COLA=1

,否则COLA='1'将为false

您应该更改您的Java代码,以使用in代替=,而不是OR生成SQL语句:

COLA in ('12001','12002')