sql_xianyu001_myxiugai.sql 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. WITH RECURSIVE excluded_ips(ip) AS(
  2. SELECT 'ip20'
  3. UNION ALL
  4. SELECT 'ip21'
  5. ),
  6. ConnectedIPs AS (
  7. -- 递归基: 初始化起始 IP 和结束 IP
  8. -- 这些是递归查询的起点
  9. SELECT
  10. 1 AS level, -- 记录当前递归层级(初始为1)
  11. 'ip0' AS from_ip, -- 起始 IP
  12. NULL AS to_ip, -- 初始时没有 to ip
  13. 0 AS addition_info -- 初始时没有标记为连接数过多
  14. UNION ALL
  15. SELECT
  16. 1 AS level, -- 记录当前递归层级(初始为1)
  17. 'ip1' AS from_ip, -- 起始 IP
  18. NULL AS to_ip, -- 初始时没有 to ip
  19. 0 AS addition_info -- 初始时没有标记为连接数过多
  20. -- 递归步骤:查找与已知 IP 相连的其他 IP
  21. UNION ALL
  22. SELECT
  23. ConnectedIPs.level + 1 AS level, -- 下一层级的递归层级(当前层级+1)
  24. ConnectedIPs.from_ip AS from_ip, -- 当前层级的 from ip
  25. table_01.to_ip AS to_ip, -- 新的 to ip
  26. CASE
  27. -- 检査当前 IP 的连接数是否超过s
  28. WHEN (SELECT COUNT(*) FROM table_01 WHERE table_01.from_ip = ConnectedIPs.from_ip OR table_01.to_ip = ConnectedIPs.from_ip) >= 5 THEN 1
  29. ELSE 0
  30. END AS addition_info
  31. FROM ConnectedIPs
  32. JOIN table_01 ON (table_01.from_ip = ConnectedIPs.from_ip OR table_01.to_ip = ConnectedIPs.from_ip)
  33. -- 递归条件:确保递归深度不超过最大值并且新Ip不在排除列表中
  34. WHERE ConnectedIPs.level < 5 -- 最大递归深度为5
  35. AND NOT EXISTS (SELECT 1 FROM excluded_ips WHERE excluded_ips.ip = table_01.from_ip OR excluded_ips.ip = table_01.to_ip)
  36. )
  37. -- 选择最终结果
  38. SELECT
  39. ConnectedIPs.level,
  40. ConnectedIPs.from_ip,
  41. ConnectedIPs.to_ip,
  42. NULL AS unique_hash, -- 需要替换为你实际的 unique hash 生成逻辑
  43. CURRENT_TIMESTAMP AS time, -- 当前时间戳作为时间字段
  44. NULL AS data, -- 需要替换为你实际的数据
  45. NULL AS from_pos, -- 需要替换为你实际的位置信息
  46. NULL AS to_pos, -- 需要替换为你实际的位置信息
  47. ConnectedIPs.addition_info -- 标记是否连接数过多
  48. FROM ConnectedIPs
  49. WHERE ConnectedIPs.level <= 5; -- 确保只选择不超过最大递归深度的结果