开发者

How to select only those rows which have more than one of given fields with values

Is there some elegant way to do that, without a big WHERE with lots of AND and OR? For example there are 4 columns: A, B, C, D. For each row the columns have random integer values. I need to select only those rows which have more than one column with a non-zero value. For example (1,2,3,4) and (3,4,0,0) should get selected, however (0,0,7,0) should not be selected (ther开发者_C百科e are no rows that have zeros only).

PS. I know how this looks but the funny thing is that this is not exam or something, it's a real query which I need to use in a real app :D


SELECT  *
FROM    mytable
WHERE   (0, 0, 0) NOT IN ((a, b, c), (a, b, d), (a, c, d), (b, c, d))

This I believe is this shortest way, though not necessarily the most efficient.


There. No WHERE, no OR and no AND:

SELECT
   IF(`column1` != 0,1,0) +
   IF(`column2` != 0,1,0) +
   IF(`column3` != 0,1,0) +
   IF(`column4` != 0,1,0) AS `results_sum`
FROM `table`
HAVING
   `results_sum` > 1


Try

select *
from table t
where ( abs(sign(A))
      + abs(sign(B))
      + abs(sign(C))
      + abs(sign(D))
      ) > 0
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜