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

时间:2010-07-22 06:46:58

标签: insert sqlite conditional

如果我有两个表:files(id, owner)share(file_id, user),其中所有者和用户是理论用户表的主要ID,那么只有在share时才能将条目插入insert into share values (1, 2) 进行共享的用户是否拥有该文件?

这是一个精简的例子,所以我只是为执行共享操作的人使用文字 - 通常这个值来自会话。如果我有:

files:
id: 1, owner: 1

并且用户2想要查看文件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)

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

Cursor.rowcount

并且它们都是语法错误。我是从Python做的,所以在这个查询之后,我只检查{{1}}以查看它是1还是0,如果它是0,那么用户没有完成操作的权限。

如何正确编写此查询?

2 个答案:

答案 0 :(得分:8)

答案 1 :(得分:3)

好吧,我找到了一种可以做到的方法,虽然这不是我希望找到的解决方案。我可以将not null和/或外键添加到file_id表中的share列,然后尝试运行此查询:

insert into share
    values(
        (select id as file_id from files where id=1 and owner=2),
        2
    );

如果用户不拥有文件ID,那么select查询将不返回任何内容,并且not null和/或外键约束将失败,我将在Python中获得异常。

如果有人知道真正的解决方案请告诉我,使用这种方法我觉得非常脏。