我使用SQLite来玩游戏并学习更多SQL。我有一个填充如下的SQLite 3数据库:
create table playlist (id integer primary key autoincrement, name text);
create table playlistitem (id integer primary key autoincrement,
playlist_id integer, name text);
insert into playlist (name) values ("Moss");
insert into playlist (name) values ("Jen");
insert into playlistitem (playlist_id, name) values (1, "Roy");
insert into playlistitem (playlist_id, name) values (1, "Richmond");
insert into playlistitem (playlist_id, name) values (2, "Denholm");
很好,现在我在"Moss"
播放列表中有两个播放列表项,"Roy"
和"Richmond"
;我在"Jen"
播放列表中有一个项目:"Denholm"
。
我想要做的是用一个查询删除"Moss"
播放列表及其所有项目。
我看到这样的事情,但对我来说失败了:
delete playlist, playlistitem from playlist
inner join playlistitem on playlistitem.playlist_id = playlist.id
where playlist.name = "Moss";
失败:
Error: near "playlist": syntax error
我做错了什么?
答案 0 :(得分:2)
sqlite在join
语句中不支持delete
。您必须使用基于playlist_id
从第二个表中删除的单独查询,在playlist
上创建删除触发器,或者使用on delete cascade
使该引用成为外键:
create table playlistitem (
id integer primary key autoincrement,
playlist_id integer, name text,
foreign key(playlist_id) references playlist(id) on delete cascade);
然后只使用delete from playlist where name='Moss'
。
不要忘记启用外键 - pragma foreign_keys=1
(您必须在每个sqlite连接上重新启用它,例如连接后的第一个命令)。