SQLite外键(Foreign Key) 的使用例子

从SQLite 3.6.19 开始支持 外键约束。

sqlite> PRAGMA foreign_keys;
0
sqlite> PRAGMA foreign_keys = ON;
sqlite> PRAGMA foreign_keys;
1
sqlite> PRAGMA foreign_keys = OFF;
sqlite> PRAGMA foreign_keys;
0



SQLite foreign keys FAQ: Can you show me how to define foreign keys in a SQLite database table design?

The SQLite database does support foreign keys, and its foreign key syntax is similar to other databases. Here’s a quick SQLite foreign key example.

A SQLite foreign key example

To show how this works, first define two database tables that don’t have any foreign keys:

--
-- salespeople
--
CREATE TABLE salespeople (
    id INTEGER PRIMARY KEY,
    first_name TEXT NOT NULL,
    last_name TEXT NOT NULL,
    commission_rate REAL NOT NULL
);

--
-- customers
--
CREATE TABLE customers (
    id INTEGER PRIMARY KEY,
    company_name TEXT NOT NULL,
    street_address TEXT NOT NULL,
    city TEXT NOT NULL,
    state TEXT NOT NULL,
    zip TEXT NOT NULL
);

Next, define a SQLite table that has two foreign keys, one that relates a new orders table back to the customers table, and a second foreign key that relates the orders table back to the salespeople table:

--
-- orders
--
CREATE TABLE orders (
    id INTEGER PRIMARY KEY,
    customer_id INTEGER,
    salesperson_id INTEGER,
    FOREIGN KEY(customer_id) REFERENCES customers(id),
    FOREIGN KEY(salesperson_id) REFERENCES salespeople(id)
);

As you can see, the SQLite foreign key syntax is very similar to other databases.

Sample SQLite foreign key data

If you'd like to test this SQLite foreign key example in your own SQLite database, here's some sample data for each of these tables:

--
-- salespeople sample data
--
INSERT INTO salespeople VALUES (null, 'Fred', 'Flinstone', 10.0);
INSERT INTO salespeople VALUES (null, 'Barney', 'Rubble', 10.0);

--
-- customers sample data
--
INSERT INTO customers VALUES (null, 'ACME, INC.', '101 Main Street', 'Anchorage', 'AK', '99501');
INSERT INTO customers VALUES (null, 'FOOBAR', '200 Foo Way', 'Louisville', 'KY', '40207');

--
-- orders sample data
--
INSERT INTO orders VALUES (null, 1, 1);
INSERT INTO orders VALUES (null, 2, 2);

I just tested these SQLite foreign key examples on my system, using SQLite version 3.4.0, and they all work fine.



FROM:

SQLite foreign key examples

http://alvinalexander.com/android/sqlite-foreign-keys-example


SQLite从什么版本开始支持外键(Foreign Key)

http://blog.csdn.net/forlong401/article/details/43760691


  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值