find_token_relation——02方案.sql 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. -- table_01是你的实际表名。
  2. -- excludeIP是排除 IP 的表名。
  3. -- overconneinputdIPTable是存储连接数过多 IP 的表名。
  4. -- ip0和ip1是你指定的初始 IP 值。
  5. -- use mine_01;
  6. WITH RECURSIVE
  7. excludeIP(exclude_ip) AS(
  8. SELECT 'ip20'
  9. UNION ALL
  10. SELECT 'ip21'
  11. ),
  12. temp_table as (
  13. SELECT ID , time, from_ip,to_ip, data
  14. FROM table_01
  15. left join excludeIP on (table_01.from_ip = excludeIP.exclude_ip or table_01.to_ip = excludeIP.exclude_ip )
  16. WHERE
  17. excludeIP.exclude_ip IS null
  18. ),
  19. distinct_temp_table as (
  20. SELECT
  21. DISTINCT
  22. from_ip,to_ip
  23. from temp_table
  24. ),
  25. input as (from_ip,to_ip)(
  26. SELECT 'ip0' ,'ip0'
  27. UNION ALL
  28. SELECT 'ip1' ,'ip1'
  29. ),
  30. fir_res as(
  31. SELECT
  32. DISTINCT
  33. t.ID, t.time, t.from_ip, t.to_ip
  34. CASE WHEN
  35. (t.from_ip = input.from_ip AND t.to_ip = input.to_ip)
  36. OR (t.to_ip = input.from_ip AND t.from_ip = input.to_ip)
  37. THEN 0 ELSE 1 END AS addtion_info
  38. FROM distinct_temp_table t
  39. JOIN input ON t.from_ip = input.to_ip OR t.to_ip = input.from_ip
  40. WHERE input.addtion_info = 1 AND
  41. (SELECT COUNT(*) FROM distinct_temp_table sub WHERE sub.from_ip = t.from_ip OR sub.to_ip = t.from_ip) <= 10
  42. )
  43. SELECT ID, time, from_ip, to_ip, data, from_pos, to_pos, level, addtion_info
  44. FROM fir_res;
  45. -- 使用WITH RECURSIVE语句定义递归查询:
  46. -- 首先定义名为input的公共表表达式(Common Table Expression),它包含了递归查询的逻辑。
  47. -- 在初始部分,从表table_01中选择满足from_ip为指定初始 IP 之一或to_ip为指定初始 IP 之一的记录,并计算初始的level(递归层级)为 1,
  48. -- 以及根据 IP 是否在排除 IP 表中来确定addtion_info的值(用于标记该记录是否可继续用于递归)。
  49. -- 在递归部分,从表table_01中选择新的记录,这些记录的from_ip与上一层级结果的to_ip相等或者to_ip与上一层级结果的from_ip相等。
  50. -- 同时,进行一系列条件判断,确保新记录满足:addtion_info 为 1(即不是排除的 IP)、连接的 IP 数量不超过 5、新 IP 不在排除 IP 表中。并且计算新的level和addtion_info值。
  51. -- 定义排除 IP 和连接数过多 IP 的临时表:
  52. -- excluded_ips临时表通过从递归结果input中选择addtion_info为 0 的记录的from_ip和to_ip作为排除的 IP。
  53. -- overconneinputd_ips临时表从递归结果input中选择连接数超过 5 的 IP(通过子查询计算连接数)。
  54. -- 插入数据到排除 IP 表和连接数过多 IP 表:
  55. -- 使用INSERT INTO语句将excluded_ips临时表中的排除 IP 插入到excludeIP表中。
  56. -- 将overconneinputd_ips临时表中的连接数过多 IP 插入到overconneinputdIPTable表中。
  57. -- 选择最终结果集:
  58. -- 从递归结果input中选择所需的列(ID、time、from_ip、to_ip、data、from_pos、to_pos、level、addtion_info)作为最终的查询结果集。