Files
gofly-platform-services/zlt-doc/sql/tenant-descendants-queries.md
2025-10-01 03:51:53 +08:00

73 lines
2.4 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 多租户层级查询通用SQL与函数示例
适用前提:数据库有租户层级表 `sys_tenant`,字段包含:
- `tenant_id`:租户ID(主键/唯一)
- `parent_tenant_id`:父租户ID(根为空)
- `tenant_path`:层级路径(格式:`/root/child/leaf/`)
- `status`:状态(1=启用)
注意:若 `tenant_path` 存在历史不一致或不可完全信任的情况,不建议以其作为过滤条件。
推荐做法:
1) 优先使用“基于 parent_tenant_id 的递归CTE”(MySQL 8+);
2) 或在应用层通过服务接口获取子孙租户ID列表,SQL 使用 `IN (...)` 过滤(兼容 MySQL 5.7)。
## 1) 基于 parent_tenant_id 的递归CTE(MySQL 8+,推荐)
查询给定锚点租户(含自身)以及所有子孙租户ID,并用于业务表过滤(以 `tourisms` 为例):
```sql
WITH RECURSIVE tenant_tree AS (
SELECT tenant_id
FROM sys_tenant
WHERE tenant_id = #{anchorTenantId} AND status = 1
UNION ALL
SELECT t.tenant_id
FROM sys_tenant t
INNER JOIN tenant_tree tt ON t.parent_tenant_id = tt.tenant_id
WHERE t.status = 1
)
SELECT t.*
FROM tourisms t
JOIN tenant_tree tt ON t.tenant_id = tt.tenant_id
ORDER BY t.id DESC;
```
## 2) 应用层预取子孙ID + SQL IN 过滤(兼容 MySQL 5.7)
在应用层通过服务(如 `ITenantHierarchyService#getAllSubTenantIds(anchorTenantId)`)获取集合后,SQL 使用 `IN (...)`:
```sql
SELECT *
FROM tourisms t
WHERE t.tenant_id IN (
/* 应用层传入的列表:tid_1, tid_2, ... */
/* MyBatis: <foreach collection="tenantIds" item="tid" ...> */
)
ORDER BY t.id DESC;
```
## 3) 可选:封装为函数(返回JSON数组)
MySQL函数无法直接返回结果集,可返回JSON数组再在应用侧解析:
```sql
DELIMITER //
CREATE FUNCTION fn_sub_tenants(anchor VARCHAR(64)) RETURNS JSON
BEGIN
DECLARE result JSON;
SET result = JSON_ARRAY();
-- 路径法,追加所有子孙ID
SELECT JSON_ARRAYAGG(st2.tenant_id)
INTO result
FROM sys_tenant st1
JOIN sys_tenant st2 ON st2.tenant_path LIKE CONCAT(st1.tenant_path, '%')
WHERE st1.tenant_id = anchor AND st2.status = 1;
RETURN result;
END //
DELIMITER ;
```
使用:`SELECT fn_sub_tenants(#{anchorTenantId});`,在应用层把JSON解析成列表再用于IN过滤。
建议:优先采用“递归CTE(MySQL 8+)或应用层 IN 方案”;仅在必要时考虑数据库函数,以免影响查询计划与可移植性。