Create table fails if foreign keys are used in SQL

2019-03-01 05:16发布

问题:

I seriously have no idea why this php code is not creating three tables. The first and second are fine. But the third fails. The third is very similar to the second but has another field after the foreign key definition. What am I doing wrong here?

$db = new \PDO("sqlite:d:/temp/test_db.sqlite");
$db->exec("PRAGMA foreign_keys = 'ON'");


$statement = $db->query("CREATE TABLE  IF NOT EXISTS customers(
  id TEXT PRIMARY KEY NOT NULL , 
  name TEXT  
)");

$statement->execute();

$statement = $db->query("CREATE TABLE  IF NOT EXISTS appointments (
  id TEXT PRIMARY KEY NOT NULL , 
  customer TEXT   , 
  FOREIGN KEY (customer) REFERENCES customers(id)  
)");

$statement->execute();


$statement = $db->query("CREATE TABLE  IF NOT EXISTS appointment (
  id TEXT PRIMARY KEY NOT NULL ,  
  customer TEXT   , 
  FOREIGN KEY (customer) REFERENCES customers(id),
  nextfield TEXT
)");

$statement->execute();

回答1:

According to the SQLite grammar specification, nextfield TEXT should be placed together with the other column definitions. FOREIGN KEY relates to the table-constraint section and should be defined after column definitions:

$statement = $db->query("CREATE TABLE  IF NOT EXISTS appointment (
  id TEXT PRIMARY KEY NOT NULL ,  
  customer TEXT   , 
  nextfield TEXT,
  FOREIGN KEY (customer) REFERENCES customers(id)
)");


回答2:

FOREIGN KEY must be coded AFTER the columns, or alternately as part of the column definition without, FOREIGN KEY(column), as the column in implied, so replace

"CREATE TABLE  IF NOT EXISTS appointment (
  id TEXT PRIMARY KEY NOT NULL ,  
  customer TEXT   , 
  FOREIGN KEY (customer) REFERENCES customers(id),
  nextfield TEXT
)"

with (table constraint):-

"CREATE TABLE  IF NOT EXISTS appointment (
  id TEXT PRIMARY KEY NOT NULL ,  
  customer TEXT   , 
  nextfield TEXT ,
  FOREIGN KEY (customer) REFERENCES customers(id))"

or with (column constraint):-

"CREATE TABLE  IF NOT EXISTS appointment (
  id TEXT PRIMARY KEY NOT NULL ,  
  customer TEXT  REFERENCES customers(id) , 
  nextfield TEXT)"


标签: sqlite3