Insert

SQLite 約束衝突 - 如何將數據插入此架構?

  • August 1, 2020

首先,很抱歉這個問題,但我花了幾個小時尋找解決方案,我得到的唯一東西是 Java 異常。我正在為電影開發一個小的網路爬蟲,所以我創建了這兩個表。

CREATE TABLE IF NOT EXISTS movies(
   movie_id INTEGER PRIMARY KEY,
   title VARCHAR(100) NOT NULL UNIQUE,
   info VARCHAR(250)
);

CREATE TABLE IF NOT EXISTS genres(
   genre_id INTEGER PRIMARY KEY,
   title VARCHAR(50) NOT NULL UNIQUE,
);

好吧,你可以看到是多對多的關係,所以我做了一個這樣的連接表:

CREATE TABLE IF NOT EXISTS movies_genres(
   movie_id INTEGER NOT NULL,
   genre_id INTEGER NOT NULL,
   PRIMARY KEY(movie_id, genre_id),
   FOREIGN KEY (movie_id) REFERENCES movies(movie_id),
   FOREIGN KEY (genre_id) REFERENCES genres(genre_id)
);

我正在嘗試使用(arg是方法參數)插入數據:

INSERT INTO movies_genres(movie_id, genre_id) 
SELECT m.movie_id, g.genre_id FROM
SELECT (movie_id FROM movies WHERE title = arg) AS m
CROSS JOIN SELECT (genre_id FROM genres WHERE title = arg) AS g;

但是我得到這個SQLITE_CONSTRAINT] Abort 由於違反約束(唯一約束失敗。我不知道錯誤在哪裡,也許在架構中但我看不到錯誤。關於如何修復它的任何想法?

首先,movies_genres 中有數據嗎?

SELECT * FROM movies_genres;

如果沒有,您可以檢查任何源表中是否缺少主鍵

SELECT movie_id FROM movies GROUP BY movie_id HAVING COUNT(1) > 1;

流派也是如此。如果上面沒問題,則錯誤應該不會發生,但您可以檢查:

SELECT m.movie_id, g.genre_id 
FROM ( -- I assume the parentheses was a typo and moved it
   SELECT movie_id 
   FROM movies 
   WHERE title = arg1
) AS m
CROSS JOIN ( -- see comment above
   SELECT genre_id 
   FROM genres WHERE title = arg2
) AS g
GROUP BY m.movie_id, g.genre_id 
HAVING COUNT(1) > 1;

順便說一句,您可以將查詢簡化為:

SELECT m.movie_id, g.genre_id 
FROM movies m
JOIN genres g
   ON m.title = arg1  
  AND g.title = arg2

引用自:https://dba.stackexchange.com/questions/273029