我有两个表:
CREATE TABLE user (
ticketId integer not null,
eventId integer not null,
ticketUsed integer,
userName text not null,
FOREIGN KEY (ticketId) REFERENCES ticketType (ticketId)
);
和
CREATE TABLE ticketType (
eventId integer not null,
ticketId integer unique not null,
ticketsUsed integer,
FOREIGN KEY (eventId) REFERENCES event (eventId)
);
我正在尝试根据使用的票证更新
ticketType.ticketsUsed
UPDATE ticketType
SET ticketsUsed = (SELECT COUNT(*) FROM user as u WHERE ticketUsed=1)
WHERE ticketId = u.ticketId;
但是我得到一个错误:
错误:无此列:u.ticketId
UPDATE ticketType
SET ticketsUsed = us.count
FROM ticketType
INNER JOIN (SELECT ticketId, COUNT(*) as count FROM user WHERE ticketUsed=1 group by ticketId) us
ON us.ticketId=ticketType.ticketId
WHERE eventId = 23779;
错误:“ FROM”附近:语法错误
最佳答案
您必须将ticketId
过滤器放入子查询中:
UPDATE ticketType
SET ticketsUsed = (SELECT COUNT(*)
FROM user AS u
WHERE ticketUsed = 1
AND u.ticketId = ticketType.ticketId)