我错过了什么

时间:2014-10-29 19:04:50

标签: mysql sql database

这是我的任务:

创建一个视图FinancialStatus,显示每个拥有
的人 帐户,人员的PID和pName,以及他们的总金额 在他们的账户上减去所有到期日未付的账单。

这是我的表格:

 CREATE TABLE People (
PID INT, 
pName VARCHAR(50),
pGender CHAR(1),
pHeight FLOAT,
PRIMARY KEY (PID)
);

CREATE TABLE Accounts (
AID INT AUTO_INCREMENT, -- IDENTITY for MS-SQL
PID INT,
aDate DATE,
aBalance INT,
aOver INT,
PRIMARY KEY (AID),
FOREIGN KEY (PID) REFERENCES People(PID)
);

CREATE TABLE Bills (
BID INT AUTO_INCREMENT, -- IDENTITY for MS-SQL
PID INT,
bDueDate DATE NOT NULL,
bAmount INT,
bIsPaid BIT NOT NULL,
PRIMARY KEY (BID),
FOREIGN KEY (PID) REFERENCES People(PID)
);

到目前为止我的查询是:

create view debts as
select b.bispaid, p.pid, p.pname, sum(b.bamount) as bamount2
from bills b, people p
where p.pid = b.pid
AND b.bDueDate < curdate()
AND b.bispaid = 0
group by p.pid;

CREATE VIEW totalbal AS
    SELECT P.PID, P.pName, SUM(A.aBalance) as bal
    FROM People P, Accounts A
    WHERE P.PID = A.PID
    GROUP BY P.PID;

create view FinancialStatus as
select p.pid, p.pName, (t.bal - d.bamount2) as remains
from totalbal t, debts d, people p
where p.pid = d.pid
AND p.pid = t.pid;
-- group by p.pid;

select * from   FinancialStatus;

这就是错误:

FinancialStatus视图返回右表,除非此人没有过去duedate的账单,例如:

John:账户余额为1000美元,他的账单超过duedate为400 $然后FinancialStatus视图返回正确的结果:

...
4   Doe    346$
5   John    600$
6   Boe     1900$
...

这是出错的时候:

John:账户余额为1000美元,没有账单超过duedate

 ...
    4   Doe    346$
                        <-here is supposed to be : 5    John    1000$
    6   Boe    1900$
    ...

我错过了什么? :)

1 个答案:

答案 0 :(得分:0)

我认为您必须进行左连接,因为debts视图没有John的记录。

create view FinancialStatus as
select p.pid, p.pName, (t.bal - IFNULL(d.bamount2, 0)) as remains
from totalbal t
inner join people p on p.pid = t.pid
left join debts d on p.pid = d.pid

注意我没有使用MySql的经验,所以我不确定语法是否100%准确。