【问题标题】:Relational Algebra Banking Database关系代数银行数据库
【发布时间】:2017-01-31 03:04:16
【问题描述】:

我有一个银行数据库的关系模式

Customer(custid PK, name, city, streetaddr, province)

Account(acctid PK, custid, atype, startdate, balance, branchid), (custid ref Customer, branchid ref Branch)

Branch(branchid PK, mgrid, city, streetaddr, province), (mgrid ref Employees.empid)

Employees(empid PK, name, branchid, salary, city, streetaddr, province), (branchid ref Branch)

Transactions(tid PK, acctid, transtype, transdate, transamount, branchid) (acctid ref Account, branchid ref Branch)

我正在尝试查找今年仅进行一次交易的客户的所有“储蓄”帐户 ID、客户姓名和客户 ID

显然我需要使用交易、帐户和客户表。我加入 Accounts with Transactions 以查看所有进行过一笔或多笔交易的账户,但我无法找到“仅一笔”交易的规范。我觉得我需要使用设置差异,但仍然无法考虑。

【问题讨论】:

  • 请参考您的意思是什么关系代数。甚至 关系 也不同,更不用说运算符了。我用 SQL 回答了你的问题,但如果你传达关系和运算符的相关概念,我可以给出一个 RA 版本。

标签: mysql sql relational-database relational-algebra


【解决方案1】:

可能是这样的:

select a.acctid, c.custid, c.name
from account a
inner join (
    select acctid
    from transactions
    where year(transdate) = year(curdate())
    group by acctid
    having count(tid) = 1
) t on a.acctid = t.acctid
inner join customer c
on a.custid = c.custid
where a.atype = 'savings';

【讨论】:

    【解决方案2】:

    这涉及“self-join”。是的,我们“使用设置差异”。

    一年中有1笔交易的acctids是有一些交易的MINUS至少有2笔交易。前者在Transactions。后者是Transactions(tid, acctid, transtype, transdate, transamount, branchid) AND Transactions(tid2, acctid, transtype2, transdate, transamount2, branchid2) AND tid <> tid2。即Transactions NATURAL JOIN RESTRICT tid <> tid2 RENAME tid\tid2, transtype\transtype2, transamount\transamount2, branchid\branchid2 Transactions。 (你可以在MINUS 之前PROJECT 离开transtypetransamountbranchid 而不是RENAME 他们。)

    在 SQL 中可能最简单的方法是 group 今年的事务 by acctid 并选择组 having count(tid) > 1。 (@GurV 的回答确实如此。)

    但是,我将解决“寻找“唯一”交易规范的问题。

    一年中有1笔交易的acctids是有一些交易减去至少有2笔交易的那些。前者在Transactions中。后者是t1.acctids 中的Transactions(t1.tid, ...) and Transactions(t2.tid, ...) and t1.tid <> t2.tid and t1.acctid = t2.acctid and t1.transdate = t2.transdate。即Transactions t1 join Transactions t2 on t1.tid <> t2.tid and t1.acctid = t2.acctid where t1.transdate = t2.transdate

    select a.acctid, c.custname, c.custid
    from Transactions t
    and t.acctid not in (
        select t1.acctid
        from Transactions t1
        join Transactions t2
        on t1.tid <> t2.tid
        and t1.acctid = t2.acctid and t1.transdate = t2.transdate)
    join Account a on t.acctid = a.acctid
    join Customer c on a.custid = c.custid
    where a.atype = 'savings'
    and t.transdate = 2017
    

    MySQL 中没有 SQL except,但除了in,您还可以使用left joinnot exists

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-16
      • 1970-01-01
      • 1970-01-01
      • 2013-03-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多