SQLite,我的引用不起作用

时间:2013-07-01 17:13:59

标签: database sqlite reference indexing constraints

我有一个问题。 我想用3个外键创建一个表

PRAGMA foreign_keys = ON;
CREATE TABLE "Dipendente" ("idDipendente" INTEGER PRIMARY KEY AUTOINCREMENT, 
                                                 "nome" VARCHAR NOT NULL, 
                                                 "cognome" VARCHAR NOT NULL , 
                                                 "email" VARCHAR NOT NULL  UNIQUE , 
                                                 "password" VARCHAR NOT NULL , 
                                                 "tipo" VARCHAR NOT NULL );


CREATE TABLE "Prodotto" ("idProdotto" INTEGER PRIMARY KEY AUTOINCREMENT,
                                             "nome" VARCHAR NOT NULL UNIQUE,
                                             "qta" INTEGER NOT NULL,
                                             "prezzoUnita" FLOAT NOT NULL );

CREATE TABLE "Fondo" ("idFondo" INTEGER PRIMARY KEY AUTOINCREMENT,
                                        "nome" VARCHAR NOT NULL UNIQUE,
                                        "fondoDisponibile" FLOAT NOT NULL );

CREATE  TABLE IF NOT EXISTS "Acquisto" (
    `idAcquisto`  INTEGER PRIMARY KEY NOT NULL ,
    `idDipendente` INTEGER NOT NULL DEFAULT -1,
    `idProdotto` INTEGER NOT NULL DEFAULT -1,
    `idFondo` INTEGER NOT NULL DEFAULT -1,
    `qta` INTEGER NOT NULL ,
    `dataAcquisto` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ,

   CONSTRAINT `fk_acquisto_dipendente`
    FOREIGN KEY (`idDipendente` )
      REFERENCES `Dipendente` (`idDipendente` )
         ON DELETE SET DEFAULT
         ON UPDATE NO ACTION,
   CONSTRAINT `fk_acquisto_prodotto`
     FOREIGN KEY (`idProdotto` )
       REFERENCES `Prodotto` (`idProdotto` )
         ON DELETE SET DEFAULT
         ON UPDATE NO ACTION,

  CONSTRAINT `fk_acquisto_fondo`
FOREIGN KEY (`idFondo` )
  REFERENCES `Fondo` (`idFondo` )
    ON DELETE SET DEFAULT
    ON UPDATE NO ACTION);

CREATE INDEX 'fk_acquisto_dipendente' ON 'Acquisto' ('idDipendente' ASC);
CREATE INDEX 'fk_acquisto_prodotto' ON 'Acquisto' ('idProdotto' ASC);
CREATE INDEX 'fk_acquisto_fondo' ON 'Acquisto' ('idFondo' ASC);

所以,我想通过defaul将Acquisto(idDipendente,idProdotto,idFondo)设置为-1值,但是当我在表Acquisto中删除idDipendente = 1的Dipendente行时,字段idDipendente仍然设置为1。我不知道是什么问题。

1 个答案:

答案 0 :(得分:0)

在“Acquisto”表中,您有三个外键引用。这些外键引用的每一列都有一个默认值-1,它不是(我推测)任何引用表中的有效值。

在这种特定情况下,如果您首先在“Dipendente”中插入一行,并且该行的“idDipendente”为-1,那么您可以删除“idDipendente”等于1的行。当您这样做时,您' ll在Acquisto.idDependente中找到默认值-1。

简短的故事是你的外键引用不会阻止你声明默认值为-1,但确实阻止你使用< / em>它。

要将值设置为NULL,您需要沿着这些行执行某些操作。

pragma foreign_keys = on;
create table a (id integer primary key);
insert into a values (1);
create table b (
  b_id integer primary key, 
  a_id integer references a(id) 
    on delete set null);
insert into b values (1, 1);
delete from a;
select * from b;

b_id        a_id      
----------  ----------
1