簡體   English   中英

將列添加到主鍵會刪除唯一性

[英]Adding column to primary key removes uniqueness

我有大約 3400 萬行,每store_sales -ds 數據集store_sales表中有 23 列。

我有ss_item_skss_ticket_number列的composite primary key

在運行查詢SELECT count(DISTINCT <primary key>) ..我能夠看到它輸出表中存在的總行數。

現在我與primary key一起添加另一列,即ss_sold_date_sk

在此之后,如果我跑了count查詢,我得到正在打印行數的數量比以前。 有人可以通過示例向我解釋為什么會發生這種情況嗎?

TL; 博士

何時將一列添加到復合主鍵會停止使其唯一?

演示

create table mytable (c1 string,c2 string);
insert into mytable values ('A','A'),('B',null),('C',null);

select count(distinct c1) as count_distinct from mytable;

+----------------+
| count_distinct |
+----------------+
|              3 |
+----------------+

正如預期的那樣 - 3 個不同的值 - 'A'、'B' 和 'C'


select count(distinct concat(c1,c2)) as count_distinct from mytable;

+----------------+
| count_distinct |
+----------------+
|              1 |
+----------------+
    

正如預期的那樣。 為什么? - 見下一個查詢


select c1,c2,concat(c1,c2) as concat_c1_c2 from mytable;

+----+------+--------------+
| c1 |  c2  | concat_c1_c2 |
+----+------+--------------+
| A  | A    | AA           |
| B  | NULL | NULL         |
| C  | NULL | NULL         |
+----+------+--------------+

與 NULL 連接產生 NULL


select count(distinct c1,c2) as count_distinct from mytable;

+----------------+
| count_distinct |
+----------------+
|              1 |
+----------------+

漏洞!!


這是一個解決該錯誤的方法:

select count(distinct struct(c1,c2)) as count_distinct from mytable;

+----------------+
| count_distinct |
+----------------+
|              3 |
+----------------+

暫無
暫無

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

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