语法错误:带有计数和内部联接的SQL更新

时间:2013-09-06 09:07:16

标签: sql sqlite

我有两张桌子:

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

1 个答案:

答案 0 :(得分:2)

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

UPDATE ticketType
SET ticketsUsed = (SELECT COUNT(*)
                   FROM user AS u
                   WHERE ticketUsed = 1
                     AND u.ticketId = ticketType.ticketId)