Mysql
 sql >> Database >  >> RDS >> Mysql

Relazione tra 2 colonne

Potresti utilizzare un totale parziale in una sottoquery per aiutarti con le versioni precedenti a mysql 8.0

drop table if exists t;
create table t
(id int,A int,B int);
insert into t values
(1,  1 ,0),
(2,  0 ,1),
(3,  1 ,0),
(4,  1 ,0),
(5,  1 ,0),
(6,  1 ,1),
(7,  1 ,0),
(8,  1 ,1),
(9,  1 ,1),
(10, 1 ,0),
(11, 1 ,1),
(12, 1 ,0),
(13, 1 ,1),
(14, 1 ,1),
(15, 1 ,1),
(16, 0 ,1);

select t1.id,t1.a,t1.b
from 
(
select t.*,
        if(t.a = 1, @rt:[email protected]+1,@rt:=0) rt
from t
cross join (select @rt:=0) r
order by t.id
) t1 
where t1.rt >= 10;

+------+------+------+
| id   | a    | b    |
+------+------+------+
|   12 |    1 |    0 |
|   13 |    1 |    1 |
|   14 |    1 |    1 |
|   15 |    1 |    1 |
+------+------+------+
4 rows in set (0.00 sec)