简体   繁体   English

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

[英]Create table fails if foreign keys are used in SQLite

I seriously have no idea why this php code is not creating three tables.我真的不知道为什么这个 php 代码没有创建三个表。 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. 根据SQLite语法规范, nextfield TEXT应与其他列定义放在一起。 FOREIGN KEY relates to the table-constraint section and should be defined after column definitions: 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)
)");

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 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):- with(表约束): -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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