MySQL获取介于两个条件之间的ID
假设我有一张桌子MySQL获取介于两个条件之间的ID,mysql,sql,Mysql,Sql,假设我有一张桌子 +----+------------+ | id | condition | +----+------------+ | 1 | open | +----+------------+ | 2 | content | +----+------------+ | 3 | content | +----+------------+ | 4 | close | +----+------------+ | 5 | nocontentx | +
+----+------------+
| id | condition |
+----+------------+
| 1 | open |
+----+------------+
| 2 | content |
+----+------------+
| 3 | content |
+----+------------+
| 4 | close |
+----+------------+
| 5 | nocontentx |
+----+------------+
| 6 | nocontenty |
+----+------------+
| 7 | open |
+----+------------+
| 8 | content |
+----+------------+
| 9 | close |
+----+------------+
| 10 | nocontentz |
+----+------------+
| 11 | open |
+----+------------+
| 12 | content |
+----+------------+
我想得到一个新的表,在那里我可以得到ID,即close和open之间的第一个和最后一个值。请注意,这两个条件之间的值是动态的,我无法通过NoContentWhather进行搜索
比如我得到这张桌子:
+----+----------+--------+
| id | start_id | end_id |
+----+----------+--------+
| 1 | 5 | 6 |
+----+----------+--------+
| 2 | 10 | 10 |
+----+----------+--------+
提前谢谢
可以使用相关子查询执行此操作:
select (@rn := @rn + 1) as id,
id as startid,
(select id
from atable a2
where a2.id > a.id and
a2.condition = 'close'
order by a2.id asc
limit 1
) as end_id
from atable a cross join
(select @rn := 0) vars
where a.condition = 'open';
正在工作的SQL小提琴是
注意,这也会返回第三个open。如果不需要,则在查询的末尾添加end_id不为null
编辑:
如果您知道ID是连续的,您可以从上面的查询中添加和减去1:
select (@rn := @rn + 1) as id,
id+1 as startid,
(select id
from atable a2
where a2.id > a.id and
a2.condition = 'open'
order by a2.id asc
limit 1
) - 1 as end_id
from atable a cross join
(select @rn := 0) vars
where a.condition = 'close';
您也可以用另一种方式来实现这一点,即计算任何给定行之前打开和关闭的数量,并将其用作组标识符。根据您的数据结构,每个其他组都是您需要的:
select grp, min(id), max(id)
from (select t.*,
(select sum(t2.condition in ('open', 'close'))
from t t2
where t2.id <= t.id
) as grp
from t
) t
where t.condition not in ('open', 'close') and
grp % 2 = 0
group by grp;
它不起作用。首先,select id需要是select minid,所以它只返回一个id。但是它返回了错误的id。看,他想要第一行和最后一行的ID在关闭和打开之间,他不想要关闭和打开行的ID本身。@kairos。我一定是把asc换成了desc,然后卡在那里了。正确的排序顺序是asc。使用asc也不起作用,因为它给了我打开和关闭之间的ID,而不是关闭和打开之间的相反:很抱歉,即使我颠倒了两个条件:我必须删除第一个和最后一个ID,因为我只希望ID在这些标记之外