SQLite foreign key examples

來源:互聯網
上載者:User

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

First, we 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, we define a SQLite table that has two foreign keys, one that relates our 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.

原文地址:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.