我使用查询来检索具有特定列名的表列表:
select name from sqlite_master where type='table' and sql like '%unique_col_id%';
因此,它返回一个表名列表,例如table_1,table_2,table_3 ..
我想删除上表中所有行,其中unique_col_id等于特定值:
DELETE FROM table_1 where unique_col_id=3;
DELETE FROM table_2 where unique_col_id=3;
DELETE FROM table_3 where unique_col_id=3;
有没有办法在一个查询中删除所有表?我的意思是集成两个查询(搜索表并删除所有这些查询与unique_col_id = 3 ...)
由于
答案 0 :(得分:6)
虽然我确信您可以通过某种方式在一个声明中完成所有这些操作,但最好使用transactions和/或triggers。
事务允许您将一堆语句组合在一起,以便在它们全部运行之前不会保存任何内容。在交易完成之前,没有其他流程会看到您的更改。如果出现错误或您的流程在交易过程中死亡,则会抛弃所有更改。这避免了一大堆问题。使用事务可以让你使用简单的语句,而不是试图将所有内容粉碎成一个无法维护的混乱。
begin;
DELETE FROM table_1 where unique_col_id=3;
DELETE FROM table_2 where unique_col_id=3;
DELETE FROM table_3 where unique_col_id=3;
commit;
与触发器相称。这使得数据库可以在发生某些事情时自动执行操作,例如当您从一个表中删除列时,它可以从其他表中删除相关信息。最常见的方法是设置ON DELETE CASCADE
on your foreign keys。
# This is necessary in SQLite else foreign keys will be ignored
sqlite> pragma foreign_keys = on;
# Make two tables with a relationship and set it ON DELETE CASCADE
sqlite> create table addresses ( id INTEGER PRIMARY KEY, address TEXT, person REFERENCES people(id) ON DELETE CASCADE );
sqlite> create table people ( id INTEGER PRIMARY KEY, name TEXT );
# Add a row with a relationship.
sqlite> insert into people (name) VALUES ("Foo Bar");
sqlite> select * from people;
1|Foo Bar
sqlite> insert into addresses (address, person) VALUES ("123 Foo St", 1);
sqlite> select * from people join addresses on addresses.person = people.id;
1|Foo Bar|1|123 Foo St|1
# Delete the parent row and the child (address) is also deleted.
sqlite> delete from people where id = 1;
sqlite> select * from people;
sqlite> select * from addresses;
这更加强大。对数据库进行更改的人不需要知道所有细节,数据库会为他们负责。
答案 1 :(得分:0)
删除所有表格的方法
public void dropAllTables() {
// query to obtain the names of all tables in your database
SQLiteDatabase db = this.getWritableDatabase();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table'", null);
List<String> tables = new ArrayList<>();
// iterate over the result set, adding every table name to a list
while (c.moveToNext()) {
tables.add(c.getString(0));
}
// call DROP TABLE on every table name
for (String table : tables) {
String dropQuery = "DROP TABLE IF EXISTS " + table;
db.execSQL(dropQuery);
}
}
答案 2 :(得分:-2)
您需要在此处进行如下所示的交易查询:
begin transaction
delete from fkTable where fk = @id delete from pkTable where pk = @id
commit