有这样的表:
Table: statuses
ID | status
----|---------
777 | 1
675 | 1
651 | 0
611 | 1
600 | 0
554 | 1
443 | 0
323 | 0
222 | 1
112 | 1
如何仅选择行中两个(或更多)状态为0的行? (在样本情况下仅为443,323),并按照第一个ID进行分组。
所以输出结果为:
ID | status | group
----|--------|---------
443 | 0 | 443
323 | 0 | 443
答案 0 :(得分:2)
如果无法使用编程方法,您可以尝试此查询(尽管性能会更差)。
select
s.id,
0 as status,
group_field.id as group
from
statuses s,
(select id from statuses where status = 0 group by id having count(1) > 1 limit 1) group_field
where
s.id in(select id from statuses where id = 0 group by id having count(1) > 1)
答案 1 :(得分:1)
select
id, STATUS,
@st_order:=if(@pre_st!=status,0,@st_order+1) as status_order,
@group_leader:=if(@pre_st!=status,id,@group_leader) as group_leader,
@pre_st:=status
from statuses,(select @st_order:=-1, @pre_st:=-1, @group_leader:=-1) val
这个sql为你提供了输出
ID,
状态,
行号继续相同的状态,
同一地位的组长,
无用的最后一栏
根据您的输入,前四列输出为
ID |状态|状态行号|状态组负责人
777 | 1 | 0 | 777个
675 | 1 | 1 | 777个
651 | 0 | 0 | 651个
611 | 1 | 0 | 611个
600 | 0 | 0 | 600个
554 | 1 | 0 | 554个
443 | 0 | 0 | 443个
323 | 0 | 1 | 443个
222 | 1 | 0 | 222个
112 | 1 | 1 | 222
所以你可以在外部选择中做任何你想做的事。
答案 2 :(得分:1)
您可以通过使用子查询使用少量逻辑来实现此目的
set @cnt=0;
set @id=-1;
SELECT
t3.id, t3.status, t3.dup_id AS `group`
FROM
(SELECT
id,
status,
IF(status = 0, @cnt:=@cnt + 1, @cnt:=0) AS great,
IF(@cnt = 1, @id:=id, IF(status = 0, @id, - 1)) AS dup_id
FROM
statuses) t3
WHERE
t3.dup_id IN (SELECT
t1.dup_id
FROM
(SELECT
id,
status,
IF(status = 0, @cnt:=@cnt + 1, @cnt:=0) AS great,
IF(@cnt = 1, @id:=id, IF(status = 0, @id, - 1)) AS dup_id
FROM
statuses) t1
GROUP BY t1.dup_id
HAVING COUNT(t1.dup_id) > 1
AND t1.dup_id != - 1);
结果将如预期那样
id | status | group
----|--------|---------
443 | 0 | 443
323 | 0 | 443