How to select only those rows that have several fields that have values

Is there an elegant way to do this, without a big one WHEREwith a lot of ANDand 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 that have more than one column with a non-zero value. For example, you should select (1,2,3,4) and (3,4,0,0), however (0,0,7,0) should not be selected (there are no lines that have only zeros).

PS. I know how it looks, but it’s funny that this is not an exam or something else, this is a real request that I need to use in a real application: D

+3
source share
3 answers

. WHERE, no OR 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
+1
SELECT  *
FROM    mytable
WHERE   (0, 0, 0) NOT IN ((a, b, c), (a, b, d), (a, c, d), (b, c, d))

, , .

+2

Try

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

Source: https://habr.com/ru/post/1788574/


All Articles