123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- -- table_01是你的实际表名。
- -- excludeIP是排除 IP 的表名。
- -- overconneinputdIPTable是存储连接数过多 IP 的表名。
- -- ip0和ip1是你指定的初始 IP 值。
- -- use mine_01;
- WITH RECURSIVE
- excludeIP(exclude_ip) AS(
- SELECT 'ip20'
- UNION ALL
- SELECT 'ip21'
- ),
- temp_table as (
- SELECT ID , time, from_ip,to_ip, data
- FROM table_01
- left join excludeIP on (table_01.from_ip = excludeIP.exclude_ip or table_01.to_ip = excludeIP.exclude_ip )
- WHERE
- excludeIP.exclude_ip IS null
- ),
- distinct_temp_table as (
- SELECT
- DISTINCT
- from_ip,to_ip
- from temp_table
- ),
- input as (from_ip,to_ip)(
- SELECT 'ip0' ,'ip0'
- UNION ALL
- SELECT 'ip1' ,'ip1'
- ),
- fir_res as(
- SELECT
- DISTINCT
- t.ID, t.time, t.from_ip, t.to_ip
- CASE WHEN
- (t.from_ip = input.from_ip AND t.to_ip = input.to_ip)
- OR (t.to_ip = input.from_ip AND t.from_ip = input.to_ip)
- THEN 0 ELSE 1 END AS addtion_info
- FROM distinct_temp_table t
- JOIN input ON t.from_ip = input.to_ip OR t.to_ip = input.from_ip
- WHERE input.addtion_info = 1 AND
- (SELECT COUNT(*) FROM distinct_temp_table sub WHERE sub.from_ip = t.from_ip OR sub.to_ip = t.from_ip) <= 10
-
- )
-
- SELECT ID, time, from_ip, to_ip, data, from_pos, to_pos, level, addtion_info
- FROM fir_res;
- -- 使用WITH RECURSIVE语句定义递归查询:
- -- 首先定义名为input的公共表表达式(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临时表通过从递归结果input中选择addtion_info为 0 的记录的from_ip和to_ip作为排除的 IP。
- -- overconneinputd_ips临时表从递归结果input中选择连接数超过 5 的 IP(通过子查询计算连接数)。
- -- 插入数据到排除 IP 表和连接数过多 IP 表:
- -- 使用INSERT INTO语句将excluded_ips临时表中的排除 IP 插入到excludeIP表中。
- -- 将overconneinputd_ips临时表中的连接数过多 IP 插入到overconneinputdIPTable表中。
- -- 选择最终结果集:
- -- 从递归结果input中选择所需的列(ID、time、from_ip、to_ip、data、from_pos、to_pos、level、addtion_info)作为最终的查询结果集。
|