gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 06:31:00 25 4
gpt4 key购买 nike

如果我有两个表:files(id, owner)share(file_id, user),其中 owner 和 user 将是理论用户表中的主要 ID ,只有当进行共享的用户拥有该文件时,我如何才能将条目插入到 share 中?

这是一个精简的例子,所以我将只使用文字来表示执行共享操作的那个——通常这个值来自一个 session 。所以如果我有:

files:id: 1, owner: 1

and user 2 wants to see file 1, I would use this query:

insert into share values (1, 2)

但这是不允许的——用户 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)

而且都是语法错误。我是从 Python 执行此操作的,因此在查询之后,我将检查 Cursor.rowcount 以查看它是 1 还是 0,如果是 0,则用户没有权限完成操作。

如何正确编写此查询?

最佳答案

请允许我提出我的方法作为答案:

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

Share 表中不需要 not null 子句或外键,没有异常(exception)。

关于如果 sqlite3 满足条件,则插入到表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3306393/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com