我有4个表:参加者,历史记录,参与者_用户和余额。 Tables History和Attendee_Owes有FK引用Attendees PK。
历史记录包含与会者的所有付款记录。
Attendee_Owes仅为历史记录表中的每位与会者保留最后一条记录。
这两个表的模式是:
sqlite> .schema history
CREATE TABLE HISTORY(
HISTORY_ID INTEGER PRIMARY KEY,
LAST_PAYMENT_DATE VARCHAR NOT NULL,
CURRENT_PAYMENT_DATE VARCHAR NOT NULL,
SUBSIDY VARCHAR(1) NOT NULL,
WEEKLY_PAYMENT REAL NOT NULL,
AMOUNT_PAID REAL NOT NULL,
HISTORY_BALANCE REAL NOT NULL,
HIST_ATTENDEE_ID INTEGER,
FOREIGN KEY(HIST_ATTENDEE_ID) REFERENCES ATTENDEES(ATTENDEE_ID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
sqlite> .schema attendee_owes
CREATE TABLE ATTENDEE_OWES(
OWES_ID INTEGER PRIMARY KEY,
ATTENDEE_OWES_BALANCE REAL NOT NULL,
OWES_ATTENDEE_ID INTEGER,
FOREIGN KEY(OWES_ATTENDEE_ID) REFERENCES ATTENDEES(ATTENDEE_ID)
ON DELETE CASCADE
ON UPDATE CASCADE
);
我的问题是删除历史记录时触发的触发器。
CREATE TRIGGER after_history_delete
AFTER DELETE ON history
BEGIN
UPDATE ATTENDEE_OWES SET ATTENDEE_OWES_BALANCE = (SELECT HISTORY_BALANCE FROM HISTORY ORDER BY HISTORY_ID DESC LIMIT 1) WHERE OWES_ATTENDEE_ID = HIST_ATTENDEE_ID;
END;
我在UPDATE语句结束时收到错误:没有这样的列:HIST_Attendee_ID
我试过了:
UPDATE ATTENDEE_OWES SET ATTENDEE_OWES_BALANCE = (SELECT HISTORY_BALANCE FROM HISTORY ORDER BY HISTORY_ID DESC LIMIT 1) WHERE OWES_ATTENDEE_ID = HISTORY.HIST_ATTENDEE_ID;
和
UPDATE ATTENDEE_OWES SET ATTENDEE_OWES_BALANCE = (SELECT HISTORY_BALANCE FROM HISTORY ORDER BY HISTORY_ID DESC LIMIT 1) WHERE OWES_ATTENDEE_ID = HISTORY(HIST_ATTENDEE_ID);
但我仍然收到错误,告诉我没有这样的专栏。
我已经尝试过我所知道的一切。任何建议都将不胜感激。
答案 0 :(得分:3)
让我们以更方便的方式查看您的SQL:
UPDATE ATTENDEE_OWES SET
ATTENDEE_OWES_BALANCE = (
SELECT HISTORY_BALANCE
FROM HISTORY
ORDER BY HISTORY_ID DESC LIMIT 1)
WHERE
OWES_ATTENDEE_ID = HIST_ATTENDEE_ID;
我们可以看到OWES_ATTENDEE_ID = HIST_ATTENDEE_ID与表HISTORY未知的最顶层相关。 正确的查询必须是:
UPDATE ATTENDEE_OWES SET
ATTENDEE_OWES_BALANCE = (
SELECT HISTORY_BALANCE
FROM HISTORY
WHERE OWES_ATTENDEE_ID = HIST_ATTENDEE_ID
ORDER BY HISTORY_ID DESC LIMIT 1)