我正在尝试在 sql.js 中创建两个表,但存在关于外键约束的错误。创建第一个没有问题table

I'm trying to create Two Tables in sql.js but there is an error regarding foreign key constraint. there is no problem in creating the first table

示例代码

<script>
config = {
    locateFile: filename => `sql-wasm.wasm`
  }
initSqlJs(config).then(function(SQL)
{
    //Create the database
    const db = new SQL.Database();

    //create first table - Questions (Parent Table)
    let question = "CREATE TABLE Questions(qid INT NOT NULL, qdesc CHAR, PRIMARY KEY(qid));\
        INSERT INTO Questions VALUES(1, 'set1');\
        INSERT INTO Questions VALUES(2, 'set2');\
        INSERT INTO Questions VALUES(3, 'set3');\
        INSERT INTO Questions VALUES(4, 'set4');\
        INSERT INTO Questions VALUES(5, 'set5');";
    db.run(question);
    const result = db.exec("SELECT * FROM Questions");
    console.log(result);
    
    //create second Table - Qimages (Child Table)
    let qimage = "CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,FOREIGN KEY (qid) REFERENCES Questions(qid));\
        INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_woods.jpg',1);\
        INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_5terre.jpg',1);\
        INSERT INTO Qimages VALUES('https://www.w3schools.com/howto/img_mountains.jpg',2);";
    db.run(qimage);
    const res = db.exec("SELECT * FROM Qimages");
    console.log(res);
</script>

下面是我遇到的错误

uncaught (in promise) Error: unknown column "qid" in foreign key definition

正如消息所说,Qimages 中没有 qid 列 table。我怀疑你想要:-

CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,qid INTEGER REFERENCES Questions(qid));

因此,使用外键约束声明的列级版本的 qid 列(现在已定义)的值必须在问题 table 的 qid 列中具有相应的值。

或者你可以使用:-

CREATE TABLE Qimages(img_id INT AUTO_INCREMENT, imgurl VARCHAR,qid INTEGER, FOREIGN KEY (qid) REFERENCES Questions(qid));