sql - 数据库设计——多1对多关系

标签 sql database database-design database-schema schema-design

用多个一对多关系对 1 个表建模的最佳方法是什么。

enter image description here

使用上述模式,如果 Report 包含 1 行,Grant 2 行和 Donation 12。当我将三者连接在一起时,我最终得到笛卡尔积和结果集 24。Report 加入 Grant 并创建 2 行,然后 Donation加入它以形成 24 行。

是否有更好的方法对此进行建模以避免 caresian 产品?

示例代码

DECLARE @Report
TABLE   (
        ReportID    INT,
        Name        VARCHAR(50)
        )

INSERT
INTO    @Report 
        (
        ReportID,
        Name 
        )

SELECT  1,'Report1'


DECLARE @Grant 
TABLE   (
        GrantID     INT IDENTITY(1,1) PRIMARY KEY(GrantID),
        GrantMaker  VARCHAR(50),
        Amount      DECIMAL(10,2),
        ReportID    INT
        )

INSERT
INTO    @Grant 
        (
        GrantMaker,
        Amount,
        ReportID
        )

SELECT  'Grantmaker1',10,1
UNION ALL
SELECT  'Grantmaker2',999,1


DECLARE @Donation
TABLE   (
        DonationID      INT IDENTITY(1,1) PRIMARY KEY(DonationID),
        DonationMaker   VARCHAR(50),
        Amount          DECIMAL(10,2),
        ReportID        INT
        )

INSERT
INTO    @Donation 
        (
        DonationMaker,
        Amount,
        ReportID
        )

SELECT  'Grantmaker1',10,1
UNION ALL
SELECT  'Grantmaker2',3434,1
UNION ALL
SELECT  'Grantmaker3',45645,1
UNION ALL
SELECT  'Grantmaker4',3,1
UNION ALL
SELECT  'Grantmaker5',34,1
UNION ALL
SELECT  'Grantmaker6',23,1
UNION ALL
SELECT  'Grantmaker7',67,1
UNION ALL
SELECT  'Grantmaker8',78,1
UNION ALL
SELECT  'Grantmaker9',98,1
UNION ALL
SELECT  'Grantmaker10',43,1
UNION ALL
SELECT  'Grantmaker11',107,1
UNION ALL
SELECT  'Grantmaker12',111,1

SELECT  *
FROM    @Report r
INNER JOIN
        @Grant g
        ON  r.ReportID = g.ReportID 
INNER JOIN
        @Donation d
        ON  r.ReportID = d.ReportID 

更新 1 2011-03-07 15:20

为到目前为止的反馈干杯,要添加到此场景中,还有来自一个报告表的其他 15 个一对多关系。由于各种商业原因,这些表不能组合在一起。

最佳答案

赠款和捐赠之间有任何关系吗?如果不存在,撤回显示它们之间伪关系的查询是否有意义?

我会做一个 grants 查询:

SELECT r.*, g.*
FROM @Report r
JOIN @Grant g ON r.ReportID = g.ReportID

还有一个用于捐赠:

SELECT r.*, d.*
FROM @Report r
JOIN @Donation d ON r.ReportID = d.ReportID

然后让您的应用程序显示适当的数据。

但是,如果 Grants 和 Donations 相似,则只需制作一个更通用的表格,例如 Contributions。

Contributions
-------------
ContributionID (PK)
Maker
Amount
Type
ReportID (FK)

现在您的查询是:

SELECT r.*, c.*
FROM @Report r
JOIN @Contribution c ON r.ReportID = c.ReportID
WHERE c.Type = 'Grant' -- or Donation, depending on the application

关于sql - 数据库设计——多1对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5221251/

相关文章:

php - SQL 查询在 LEFT JOIN 后未返回预期结果(包括架构和图片)

django - 层次结构数据的单表或多表

ruby-on-rails - Rails 3.1 数据库查询

mysql - 如何将多个锦标赛/括号类型建模到 SQL 数据库中?

mysql - 将文件关联到数据库任何表中的任何行

sql - 公共(public)表表达式有什么用?

mysql - JOIN SQL 函数结果与一张表中的多个 WHERE

database-design - DNA转换域名的最大长度是多少?

SQL:查找行之间最长的公共(public)字符串

swift - 如何在signUpInBackground时添加自定义字段: with Parse Server?