簡體   English   中英

如何從數組中查找mysql表中的缺失值

[英]how to find the missing values in a mysql table from an array

我有一個帶有varchar主鍵的表,這是其他一些表的先行鍵。

就像是:

ID-------------NAME
1011001020-----product 1
1011001022-----product 2    
1011001025-----product 3

然后,我有這個數組

array(
    '1011001020',
    '1011001022',
    '1011001025',
    'x',
    'y'
)

該數組將用於在帶有FK的另一個表中插入值,因此,如果第一個表中的值不是ID,則INSERT查詢將停止。

在嘗試插入之前,如何找到“ x”和“ y”。 我想避免從表1中選擇所有ID並進行PHP比較,因為有很多記錄。 我寧願使用MySQL方法

我建議以下過程:

  • 創建表並將所有值插入表中。
  • 刪除不匹配的值。
  • 添加外鍵約束。

第二步和第三步可以在SQL中輕松完成:

delete from temporarytable
    where tt.otherid not in (select ot.otherid from othertable ot);

alter table temporarytable
    add constraint fk_othertable foreign key (otherid) references othertable(otherid);

您可以根據需要加載數據。 為了提高速度,我建議在load data infile

試一試。 在服務器上經過測試,products是新表,僅插入了在items表的數組中找到的行。

INSERT INTO  `products` (  `name` ) 
SELECT  `name` FROM  `items` WHERE  `vendor_id` IN ( 1,2,3,4,.... )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM