sql-server - 在主表中添加客户特定记录

标签 sql-server database sql-server-2008 database-design multi-tenant

我已经设计了下表。

Now the new requirement is i need to show some Category for all the tenants. Also each tenant should able to add their new Category into the Master Category. So they can see all master + their specific categories

租户表

TenantId
Name

组表

GroupId
Name

类别表

CategoryId
Name

租户X类别

TenantId
CategoryId

我可以在上表中进行哪些更改来实现它?我在下面尝试了这个

将类别表修改为下面。

类别表

CategoryId
Name
TenantId NULL // This indicates tenant specific category

为 TenantId 和 Name 添加唯一键

然后查询

SELECT *
  FROM Category where TenantId = 1
  UNION
SELECT *
  FROM Category where TenantId IS NULL

But the problem is if two tenant only want to see a particular Category, I need to add a new row with other TenantId in Category table. This mean i am creating duplicate entry in a lookup table. Any suggestion to achieve the new requirement?

最佳答案

因此,租户 A 可能会看到:

  • (1) 主类别,
  • (2) 属于租户 A 的类别,
  • (3) 属于另一个租户且另一个租户明确允许租户 A 查看的类别

您当前的架构似乎满足要求。特别是,前两条规则确实可以使用 Category 表中可为空的 TenantId 列来实现,其中 NULL 代表主类别,非 NULL 值代表主类别。引用该类别的创建者/所有者,从而表示特定于租户的类别。 (为了更清楚起见,我可能会将该列重命名为 OwnerTenantId 之类的名称,但这可能只是我个人的想法。)

要仅检索主类别或属于指定租户的类别,您可以使用您在问题或此问题中发布的查询(这可能会产生与您的查询相同的执行计划):

SELECT
  CategoryId,
  CategoryName,
  CASE
     WHEN TenantId = @TenantId    THEN 'Mine'
     WHEN TenantId IS NULL        THEN 'Master'
  END AS Ownership
FROM Category
WHERE TenantId = @TenantId
   OR TenantId IS NULL
;

要实现第三条规则,您可以使用 TenantXCategory 表来存储租户可用的类别以及使用前两条规则可访问的类别。也就是说,如果租户 M 允许租户 N 查看租户 M 的某些类别,则类别的 Id 将与租户 N 的 Id 一起插入到 TenantXCategory 中。

因此,要查询特定租户可用的所有类别,您可以执行以下操作:

SELECT
  c.CategoryId,
  c.CategoryName,
  CASE
     WHEN c.TenantId = @TenantId    THEN 'Mine'
     WHEN c.TenantId IS NULL        THEN 'Master'
     WHEN tc.CategoryId IS NOT NULL THEN 'Someone else''s'
  END AS Ownership
FROM Category c
LEFT JOIN TenantXCategory tc
  ON tc.CategoryId = c.CategoryId AND tc.TenandId = @TenantId
WHERE c.TenantId = @TenantId
   OR c.TenantId IS NULL
   OR tc.CategoryId IS NOT NULL
;

关于sql-server - 在主表中添加客户特定记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14796849/

相关文章:

SQL Server : Storing Query Result into Variable

sql - 在部署时将大量数据导入 SQL Server (Express) 数据库

php - 如何限制每个用户的表单提交率

php - SQL Server 定期固定延迟

sql-server - 建立具有集成安全性的连接时,SSPI 握手失败,错误代码为 0x8009030c

c# - 如何解决此 SQL/C# DLL 冲突

php - 有谁知道支持复合键的 Kohana 的最佳 ORM?

mongodb - 获取有关 ObjectID 时间戳 Mongo 的最新文档

sql - TFS - 数据库部署 - 在约束上设置 CHECK 或 NOCHECK

sql - TSQL 从 xml 值中删除制表符和换行符