需要一种更简单的方法来测试sql中的许多OR

时间:2013-11-30 08:24:32

标签: mysql

在MySql中,我有一个类似......

的查询
select x,y,a,b,c,d,e from thetable where
a!= 0 OR b!= 0 OR c!=0 OR d!=0 OR e!=0

任何更短的方式来写所有这些OR?

1 个答案:

答案 0 :(得分:4)

NOT IN (set of values comma separated)

示例

select * from thetable where 0 not in ( a, b, c, d );

如果列中至少有一行0,则省略该行。

请参阅 MySQL: NOT IN ()


更新1

  

这将消除其中一个为零的任何情况。但我想选择是否其中任何一个不为零。因此,如果其中5个为0而其中一个为其他,则答案应该是真的。

可能你需要类似的东西:

select * from thetable where replace(concat(a,b,c,d,e,x,y),0,'') != '';

一个工作示例如下所示:

create table t( a int, b int, c int );
insert into t values( 1,0,2 );
insert into t values( 2,5,4 );
insert into t values( 6,10,12 );
insert into t values( 0,3,8 );
insert into t values( 11,23,0 );
insert into t values( -1,6,-90 );
insert into t values( 0,0,0 );

mysql> select *, 
              concat(a,b,c) concatenated,
              replace(concat(a,b,c),0,'') replaced
       from t;
+------+------+------+--------------+----------+
| a    | b    | c    | concatenated | replaced |
+------+------+------+--------------+----------+
|    1 |    0 |    2 | 102          | 12       |
|    2 |    5 |    4 | 254          | 254      |
|    6 |   10 |   12 | 61012        | 6112     |
|    0 |    3 |    8 | 038          | 38       |
|   11 |   23 |    0 | 11230        | 1123     |
|   -1 |    6 |  -90 | -16-90       | -16-9    |
|    0 |    0 |    0 | 000          |          |
+------+------+------+--------------+----------+
7 rows in set (0.00 sec)

使用where条件,您可以省略最后一行,因为它将所有列值都设为零。

mysql>  select * from t where replace(concat(a,b,c),0,'') != '';
+------+------+------+
| a    | b    | c    |
+------+------+------+
|    1 |    0 |    2 |
|    2 |    5 |    4 |
|    6 |   10 |   12 |
|    0 |    3 |    8 |
|   11 |   23 |    0 |
|   -1 |    6 |  -90 |
+------+------+------+
6 rows in set (0.00 sec)

请参阅 MySQL Replace function