[英]Adding column to primary key removes uniqueness
我有大約 3400 萬行,每store_sales
-ds 數據集的store_sales
表中有 23 列。
我有ss_item_sk
和ss_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.