简体   繁体   中英

Create table fails if foreign keys are used in SQLite

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();

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)
)");

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)"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM