-- table_01是你的实际表名。
-- excludeIP是排除 IP 的表名。
-- overconnectedIPTable是存储连接数过多 IP 的表名。
-- ip0和ip1是你指定的初始 IP 值。

use mine_01;
WITH RECURSIVE cte AS (
    SELECT ID, time, from_ip, to_ip, data, from_pos, to_pos, 1 AS level, 
           CASE WHEN from_ip IN (SELECT exclude_ip FROM excludeIP) OR to_ip IN (SELECT exclude_ip FROM excludeIP) THEN 0 ELSE 1 END AS addtion_info
    FROM table_01
    WHERE from_ip IN ('ip0','ip1') OR to_ip IN ('ip0','ip1')
    UNION ALL
    SELECT t.ID, t.time, t.from_ip, t.to_ip, t.data, t.from_pos, t.to_pos, cte.level + 1,
           CASE WHEN t.from_ip IN (SELECT exclude_ip FROM excludeIP) OR t.to_ip IN (SELECT exclude_ip FROM excludeIP) OR
                (t.from_ip = cte.from_ip AND t.to_ip = cte.to_ip) OR
                (t.to_ip = cte.from_ip AND t.from_ip = cte.to_ip) THEN 0 ELSE 1 END AS addtion_info
    FROM table_01 t
    JOIN cte ON t.from_ip = cte.to_ip OR t.to_ip = cte.from_ip
    WHERE cte.addtion_info = 1 AND
          (SELECT COUNT(*) FROM table_01 sub WHERE sub.from_ip = t.from_ip OR sub.to_ip = t.from_ip) <= 5 AND
          t.from_ip NOT IN (SELECT exclude_ip FROM excludeIP) AND t.to_ip NOT IN (SELECT exclude_ip FROM excludeIP)
), excluded_ips AS (
    SELECT from_ip AS exclude_ip FROM cte WHERE addtion_info = 0
    UNION ALL
    SELECT to_ip AS exclude_ip FROM cte WHERE addtion_info = 0
), overconnected_ips AS (
    SELECT from_ip AS overconnected_ip FROM cte WHERE (SELECT COUNT(*) FROM table_01 sub WHERE sub.from_ip = cte.from_ip OR sub.to_ip = cte.from_ip) > 5
    UNION ALL
    SELECT to_ip AS overconnected_ip FROM cte WHERE (SELECT COUNT(*) FROM table_01 sub WHERE sub.from_ip = cte.to_ip OR sub.to_ip = cte.to_ip) > 5
)
INSERT INTO excludeIP (exclude_ip)
SELECT exclude_ip FROM excluded_ips;

INSERT INTO overconnectedIPTable (overconnected_ip)
SELECT overconnected_ip FROM overconnected_ips;

SELECT ID, time, from_ip, to_ip, data, from_pos, to_pos, level, addtion_info
FROM cte;




-- 使用WITH RECURSIVE语句定义递归查询：
-- 首先定义名为cte的公共表表达式（Common Table Expression），它包含了递归查询的逻辑。
-- 在初始部分，从表table_01中选择满足from_ip为指定初始 IP 之一或to_ip为指定初始 IP 之一的记录，并计算初始的level（递归层级）为 1，
-- 以及根据 IP 是否在排除 IP 表中来确定addtion_info的值（用于标记该记录是否可继续用于递归）。
-- 在递归部分，从表table_01中选择新的记录，这些记录的from_ip与上一层级结果的to_ip相等或者to_ip与上一层级结果的from_ip相等。
-- 同时，进行一系列条件判断，确保新记录满足：addtion_info 为 1（即不是排除的 IP）、连接的 IP 数量不超过 5、新 IP 不在排除 IP 表中。并且计算新的level和addtion_info值。
-- 定义排除 IP 和连接数过多 IP 的临时表：
-- excluded_ips临时表通过从递归结果cte中选择addtion_info为 0 的记录的from_ip和to_ip作为排除的 IP。
-- overconnected_ips临时表从递归结果cte中选择连接数超过 5 的 IP（通过子查询计算连接数）。
-- 插入数据到排除 IP 表和连接数过多 IP 表：
-- 使用INSERT INTO语句将excluded_ips临时表中的排除 IP 插入到excludeIP表中。
-- 将overconnected_ips临时表中的连接数过多 IP 插入到overconnectedIPTable表中。
-- 选择最终结果集：
-- 从递归结果cte中选择所需的列（ID、time、from_ip、to_ip、data、from_pos、to_pos、level、addtion_info）作为最终的查询结果集。




