51

I'm creating a table with foreign key references. I'm wondering about the required syntax. Mostly I've seen the following (from http://www.sqlite.org/foreignkeys.html#fk_basics):

CREATE TABLE artist(  
  artistid    INTEGER PRIMARY KEY,  
  artistname  TEXT  
);  
CREATE TABLE track(  
  trackid     INTEGER,   
  trackname   TEXT,  
  trackartist INTEGER,  
  FOREIGN KEY(trackartist) REFERENCES artist(artistid)  
);

However, from the same site (http://www.sqlite.org/foreignkeys.html#fk_actions) I see this:

CREATE TABLE artist(  
  artistid    INTEGER PRIMARY KEY,  
  artistname  TEXT  
);  
CREATE TABLE track(  
  trackid     INTEGER,  
  trackname   TEXT,   
  trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE  
);

The latter syntax is a little more concise, but I want to know if the result is somehow different (aside from the ON UPDATE CASCADE, which of course has an effect; I only included it because I copied the code exactly from the referenced site, and because I don't know that the above syntax doesn't apply only when making such a specification). I am working in Android, in case that matters.

4

2 回答 2

42

This answer might not be related to yours but i thought it should be helpful for others who are working with android database.
IN SQLite Foreign key constraints are disabled by default (for backwards compatibility). You have to enable it explicitly using

PRAGMA foreign_keys = 1

after you establishing your connection with the database. Here's the link to the official docs that explains it in more depth. http://sqlite.org/foreignkeys.html Please navigate to enabling foreign key support in the above link.

于 2015-01-07T09:35:34.840 回答
28

See the syntax diagrams.

The first syntax is a table constraint, while the second syntax is a column constraint. In these examples, they behave the same.

You would need a table constraint for a key over multiple columns (where you do not have a single column you could attach it to).

于 2013-08-22T19:34:17.090 回答