簡體   English   中英

具有UNIQUE INDEX MySQL和NULL列的重復行

[英]Duplicated Rows with UNIQUE INDEX MySQL and NULL Columns

表后綴: ID,名稱

(3, 'com')

表域名: ID,名稱

(2, 'microsoft')

表域: id,name_code,sufix

(1, 2, 3)    -- microsoft.com

表SubDomainName:

(4, 'windows')

表子ID,名稱代碼,域

(7, 4, 1)     -- windows.microsoft.com

表電子郵件: ID,名稱,服務器

(3, 'myemail', 7)    -- myemail@windows.microsoft.com
(4, 'other', 1)      -- other@microsoft.com

這是外鍵約束的問題。 如何解析域和子域以正確創建電子郵件? 我在使用NULL值的Unique INDEX時遇到問題,例如,一種解決方案可能是:

表電子郵件: ID,名稱,子域,域

(3, 'myemail', 7, NULL)  -- myemail@windows.microsoft.com
(4, 'other', NULL, 1)    -- other@microsoft.com

(5, 'newemail', NULL, NULL)  -- will duplicated values in the table
(6, 'newemail', NULL, NULL)
(7, 'newemail', NULL, NULL)
(8, 'newemail', NULL, NULL)

(**3**, 'myemail', 7, 1)   -- myemail@windows.microsoft.com and myemail@microsoft.com

MySQL中的Unique只會檢查非NULL值是否唯一。 因此,如果您不希望有多個theese行:

(6, 'newemail', NULL, NULL)

您必須在theese的后兩個字段上放置一個唯一索引,並在其中放置非NULL(即0)以外的值

(6, 'newemail', 0, 0)

然后,MySQL將阻止多個條目。

怎么樣(5,“ newemail”,domain_id / subdomain_id,“ domain / subdomain”)

所以你可以

(5,'newemail',7,'subdomain')或(5,'newemail',1,'domain')

您仍然可以LEFT JOIN SubDomain和Domain表,但是您將基於“ domain / subdomain”字段僅從所需的數據中獲取數據。

那是快速的解決方案。 恕我直言,您的數據庫結構不是很好,可以進行優化。 您應該將所有域/子域記錄保留在一個表中,並將其用於電子郵件。 該表應為表FullDomain:id,name_code,domain_name,subdomain_name

(1, 3, 2, 4) -- windows.microsoft.com

要么

(1, 3, 2, 0) -- microsoft.com

暫無
暫無

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

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