关系代数银行数据库

时间:2017-01-31 03:04:16

标签: mysql sql relational-database relational-algebra

我有银行数据库的这种关系模式

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来查看已经进行过一次或多次交易的所有账户,但是我找不到“只有一次”交易的规格。我觉得我需要使用设置差异,但我仍然无法通过思考。

2 个答案:

答案 0 :(得分: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';

答案 1 :(得分:0)

这使“自我 - 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。 (您可以在PROJECT之前transtype离开transamountbranchidMINUS,而不是RENAME

SQL最简单的方法是group今年的交易by acctid并选择群组having count(tid) > 1。 (@ GurV的回答是这样的。)

但是,我会解决'找到“只有一个”交易规范的麻烦。

一年中有1笔交易的acctids是那些有一些交易减去至少有2笔交易的交易。前者在Transactions。后者是t1.acctidTransactions(t1.tid, ...) and Transactions(t2.tid, ...) and t1.tid <> t2.tid and t1.acctid = t2.acctid and t1.transdate = t2.transdate的{​​{1}}。即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