20240722-0725 資料庫外來鍵報錯

marverdol發表於2024-07-25

資料庫關聯查詢:

​ 有一個村莊表,每個村莊屬於一個村莊管理員,存著村莊管理員的id,村莊管理員在user_user和sys_user裡存著。

​ 查詢村莊表,是超級管理員能看到所有村莊,村莊管理員只能看到自己的村莊。

select 
v.id, v.name, v.owner_id, v.created_at, v.updated_at 
from location_village v 
join user_user u on v.owner_id = u.id 
left join sys_user su on su.TEL = u.phone 
where ${USER_ID} in (select user_id from sys_user_role where role_id = 'root') 
or su.USER_ID = ${USER_ID}

由於需要條件查詢,所以需要sys_user,sys_user只和user_user關聯,所以需要join兩個表。

select 
p.id, p.name, p.price, p.unit, f.file, 
p.description, p.is_on_sale, p.is_reviewed, 
a.name as area_name, u.name as user_name, pc.name as category_name, 
p.created_at, p.updated_at, su.USER_ID, p.area_id, p.merchant_id, 
p.category_id, pi.file_id 
from product_product p 
left join product_product_image pi on p.id = pi.product_id 
left join backstage_file f on pi.file_id = f.id 
join location_area a on p.area_id = a.id 
join user_user u on p.merchant_id = u.id 
join product_productcategory pc on p.category_id = pc.id 
join sys_user su on u.phone = su.TEL 
報錯:
'set' object is not subscriptable

錯誤原因:我把返回資料寫成return {'xx'}了,只有鍵沒有值

An error occurred: list index out of range

“list index out of range”這個錯誤通常發生在嘗試訪問列表中不存在的索引時。比如,如果你的列表只有5個元素,但你嘗試訪問第6個元素(索引為5的元素,因為索引是從0開始的),就會出現這個錯誤。

圖片id存在列表中,我沒有上傳圖片,列表為空。

An error occurred: string indices must be integers

這個錯誤資訊 "string indices must be integers" 指的是在Python中,你嘗試使用非整數型別的索引來訪問字串中的元素。在Python中,字串是一個序列,它的索引必須是整數。

例如,如果你有一個字串 s = "hello",你可以使用 s[0] 來訪問第一個字元 'h',因為0是一個整數。如果你嘗試使用非整數型別的索引,比如 s["first"],Python就會丟擲這個錯誤。

要解決這個問題,你需要確保你用來訪問字串索引的是整數。如果你的程式碼中有變數用作索引,檢查這個變數確保它是整數型別。如果需要,你可以使用 int() 函式將索引轉換為整數。

錯誤原因:我之前寫了一個處理列表的工具,列表的資料是一個個字典,現在想處理字典,沒有修改就用了,裡邊有一個for item in result,result是一個字典,所以就報錯了。

3780 - Referencing column fileid' and referenced column 'file id' in foreign key constraint product_product image_fileid_e43b9flc_fk_backstage_fileid' are incompatible.

在嘗試建立外來鍵約束時遇到了問題。具體來說,外來鍵約束中引用的列名和被引用的列名不相容。

這裡的問題很可能是列名的命名不一致導致的。在外來鍵約束中,引用的列(即子表中的列)和被引用的列(即父表中的列)必須具有完全相同的名稱和資料型別。

這是在navicat中建立外來鍵時的錯誤,被引用的欄位我是手打的,報了這個錯誤,後來手動選擇,又報了另一個錯誤:

1091 - Can't DROP 'product_product jimage_file_id_e43b9f1c_ fk_backstage_file_id'; check that column/key exists

重新整理了幾遍就好了。。。

建立新外來鍵又報了錯誤:

3780 - Referencing column file id' and referenced column file id' in foreign key constraint 'product_produce jimage _file id' are incompatible.

錯誤原因:外來鍵型別錯了,一個是int,一個是bigint

修改了型別,還是報錯,原因:兩個表中的資料不匹配,把資料全刪了就好了。

相關文章