2

我有两张桌子:

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”附近:语法错误

4

1 回答 1

2

您必须将ticketId过滤器放在子查询中:

UPDATE ticketType
SET ticketsUsed = (SELECT COUNT(*)
                   FROM user AS u
                   WHERE ticketUsed = 1
                     AND u.ticketId = ticketType.ticketId)
于 2013-09-06T09:24:53.733 回答