如果sqlite3满足条件,则插入表中

Car*_*ers 4 sqlite conditional insert

如果我有两个表:files(id, owner)并且share(file_id, user),所有者和用户将是理论用户表的主要ID,那么share只有在进行共享的用户拥有该文件时,如何插入条目?

这是一个简化的示例,因此我只使用文字作为执行共享操作的文本 - 通常此值将来自会话.所以,如果我有:

files:
id: 1, owner: 1

并且用户2想要查看文件1,我会使用此查询:

insert into share values (1, 2)
Run Code Online (Sandbox Code Playgroud)

但这是不允许的 - 用户2不拥有文件1,用户1没有.我试图在一个查询中执行此操作,但我无法弄明白.我试过了:

case when (select owner from files where id=1) is 2
    then (insert into share values (1, 2));

case (select owner from files where id=1) is 2
    then (insert into share values (1, 2));

insert into share values (1, 2)
    where 2 not in (select owner from files where id=1)
Run Code Online (Sandbox Code Playgroud)

它们都是语法错误.我是从Python做的,所以在这个查询之后,我只是检查Cursor.rowcount它是否为1或0,如果它是0,那么用户没有权限来完成操作.

如何正确编写此查询?

MPe*_*ier 8

请允许我建议我的方法作为答案:

insert into share select id,2 as file_id from files where id=1 and owner=2;
Run Code Online (Sandbox Code Playgroud)

not null您的Share表中不需要子句或外键,也不需要捕获异常.