Delete query in sqlite for child tables
I have 3 tables, like Employee, Department and开发者_如何学C Electronics tables.
Electronics table is child table for Department table and Department table is child table for Employee table.
I want to delete one record in Employee table where E_id=2 ( this is Primary key) this is Foreign key in Department table (E_id is Foreign key and Dept_id is Primary key) and Dept_id is Foreign Key in Electronics table.
First I want to delete related records in Electronics table then Department table and finally Employee table.
Please guide me how to do it.
You can read more about foreign key support in sqlite here: http://www.sqlite.org/foreignkeys.html
but you should be able to turn it on:
sqlite> PRAGMA foreign_keys = ON;
and then setup the database schema with the deletes cascading:
-- Database schema
CREATE TABLE Employee(
E_id INTEGER PRIMARY KEY,
name TEXT
);
CREATE TABLE Department(
Dept_id INTEGER PRIMARY KEY,
name TEXT,
E_id INTEGER REFERENCES Employee(E_id) ON DELETE CASCADE
);
CREATE TABLE Electronics(
Elec_id INTEGER PRIMARY KEY,
name TEXT,
Dept_id INTEGER REFERENCES Department(Dept_id) ON DELETE CASCADE
);
With all this in place and the data in the tables:
DELETE FROM Employee WHERE E_id = 2;
精彩评论