【问题标题】:SQLITE ON UPDATE ActionsSQLITE ON 更新操作
【发布时间】:2013-04-19 01:20:53
【问题描述】:

基于SQLite foreign key documentation,应该是创建两个数据库的方式,如果父字段更新,引用父字段的字段也会更新。

问题:按照以下步骤操作后,一切正常,直到最后一个命令 SELECT * FROM track; 因为结果仍然与下面的相同,因此它应该更改为最后显示的结果。

  trackid  trackname          trackartist
    -------  -----------------  -----------
    11       That's Amore       1
    12       Christmas Blues    1
    13       My Way             2  

编码:

-- Database schema
CREATE TABLE artist(
  artistid    INTEGER PRIMARY KEY, 
  artistname  TEXT
);
CREATE TABLE track(
  trackid     INTEGER,
  trackname   TEXT, 
  trackartist INTEGER REFERENCES artist(artistid) ON UPDATE CASCADE
);

sqlite> SELECT * FROM artist;
artistid  artistname       
--------  -----------------
1         Dean Martin      
2         Frank Sinatra    

sqlite> SELECT * FROM track;
trackid  trackname          trackartist
-------  -----------------  -----------
11       That's Amore       1
12       Christmas Blues    1
13       My Way             2  

sqlite> -- Update the artistid column of the artist record for "Dean Martin".
sqlite> -- Normally, this would raise a constraint, as it would orphan the two
sqlite> -- dependent records in the track table. However, the ON UPDATE CASCADE clause
sqlite> -- attached to the foreign key definition causes the update to "cascade"
sqlite> -- to the child table, preventing the foreign key constraint violation.
sqlite> UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin';

sqlite> SELECT * FROM artist;
artistid  artistname       
--------  -----------------
2         Frank Sinatra    
100       Dean Martin      

sqlite> SELECT * FROM track;
trackid  trackname          trackartist
-------  -----------------  -----------
11       That's Amore       100
12       Christmas Blues    100  
13       My Way             2  

这是为什么?

【问题讨论】:

    标签: sql database sqlite foreign-keys


    【解决方案1】:

    您应该更加小心地阅读fine manual

    2。启用外键支持
    [...]
    假设库是在启用外键约束的情况下编译的,它仍然必须由应用程序在运行时使用 PRAGMA foreign_keys 命令启用。例如:

    sqlite> PRAGMA foreign_keys = ON;
    

    默认禁用外键约束(为了向后兼容),因此必须分别为每个数据库连接单独启用。

    如果你这样说:

    sqlite> PRAGMA foreign_keys = ON;
    sqlite> UPDATE artist SET artistid = 100 WHERE artistname = 'Dean Martin';
    

    然后您将在 track 中看到您所期望的 100。当然,这假设您的 SQLite 是使用 FK 支持编译的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-20
      相关资源
      最近更新 更多