在sqlite中执行条件语句

时间:2014-07-11 15:20:52

标签: sql sqlite

SQL和Sqlite的新手,我很害怕。我需要从表A中删除一行,但前提是该行未在表B中引用。所以,我想我需要做这样的事情:

delete from tableA 
   where (col1 = 94) and 
   (select count(*) from tableB (where col2 = 94) = 0);

正确的方法是什么?

或者,我可以通过两个步骤从C执行此操作,首先检查该行是否未被引用,然后将其删除。这会更好吗?我对此犹豫不决是因为我需要在C代码中围绕几个步骤放置sqlite3_mutex,这可能不如执行单个更复杂的语句更有效。谢谢。

2 个答案:

答案 0 :(得分:1)

delete tableA
from tableA 
left join tableB on tableA.col1 = tableB.col2
where tableB.col2 is null
and tableA.col1 = 94

您可以left join这两个表,只删除那些无法在它们之间建立链接的表(tableB.col2 is null)。

或者你可以做

delete from tableA 
where col1 = 94
and not exists
(
   select 1 from tableB where col2 = 94
)

答案 1 :(得分:1)

你的方法非常接近。括号在错误的地方:

delete from tableA 
   where (col1 = 94) and 
         (select count(*) from tableB where col2 = 94) = 0;

例如,SQL不允许在where之前使用paren。

但我建议您了解外键。这些是SQL中有用的构造。 SQLite文档是here

外键约束会让数据库在从tableA删除行时自动执行此检查。 delete会返回错误,但它会有意义 - 类似于"您无法删除此行,因为另一行引用了该行"。