如果在SQLite中使用外键,则创建表失败

时间:2017-12-29 08:16:50

标签: sqlite

我真的不知道为什么这个PHP代码没有创建三个表。第一和第二都很好。但第三个失败了。第三个与第二个非常相似,但在外键定义之后有另一个字段。我在这做错了什么?

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

2 个答案:

答案 0 :(得分:2)

根据SQLite grammar规范,nextfield TEXT应与其他列定义放在一起。 FOREIGN KEYtable-constraint部分相关,应在列定义后定义:

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

答案 1 :(得分:1)

FOREIGN KEY必须在列之后进行编码,或者作为列定义的一部分进行编码而不使用FOREIGN KEY(列)作为隐含的列,因此替换

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

或(列约束): -

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