2013-03-20 69 views
0

mySQL查詢 - 我有一個包含大約1000行的表'database'。'table_product_options'。此表應該包含每個'product_id'的4x行 - 分配給每個'customer_group'的相同產品(如下所示)。這應該相當於每個customer_group約250行。mySQL從重複的行中查找缺失的項目

然而,我已經運行在每個「customer_group」一個COUNT,並發現有遺漏的條目的團體少數一個 + Ç(250行總計每個團體b + d,但只有245行用於組a + c)。

+----------------+----------------+ 
| product_id  | customer_group | 
+----------------+----------------+ 
|  1  |  a  | } 
|  1  |  b  | } 
|  1  |  c  | }-each 'product_id' has 4x 'customer_group' attached 
|  1  |  d  | } 
|  2  |  a  | 
|  2  |  b  | 
|  2  |  c  | << 1 missing entry (customer_group = d) 
|  3  |  a  | << 3 missing entries (customer_group = b, c, d) 
+----------------+----------------+ 

如何運行一個SELECT查詢(或可替換的),以顯示其「PRODUCT_ID」具有小於4行分配情況?或者換句話說,我如何找到缺失的條目?

我已經嘗試過很多不同的查詢,包括SELECT與WHERE NOT EXIST結合等,但我的想法已經不多了。我修改了一堆的stackoverflow答案,但沒有一個是非常合適的,並且還沒有能夠修改語法來工作。

任何幫助將不勝感激(因爲我預計未來再次出現同樣的問題..)。我可能最終會在一張桌子上擦一擦!

+0

理想情況下,結果會是什麼樣子? – Strawberry 2013-03-20 12:19:31

+0

選擇的答案(下面)僅列出了在列表中顯示product_id的「奇怪的東西」。 – abe 2013-03-20 13:55:41

回答

0
select product_id, count(customer_group) 
from table_product_options 
group by product_id 
having count(customer_group) < 4 

您可能必須通過線切換擁有和組。我把訂單搞糊塗了。

+0

完美,非常感謝! 訂單正確:) – abe 2013-03-20 13:50:16

0

撰寫查找遺漏組的可能組合。

select product_id, indicator, case when indicator = 1 
            case when availe = 'a' then 'b,c,d' 
            when availe = 'b' then 'a,c,d' 
            when availe = 'c' then 'a,b,d' 
            else 'a,b,c' end 
           case when indicator = 2 
            case when availe = 'a,b' then 'c,d' 
       //Like wise Give the possible combination for finding missing group 
           end as missing_group 
from 
(select product_id, count(customer_group) as indicator, group_concat(customer_group) as availe 
from table_product_options 
group by product_id) a where indicator < 4 
+0

感謝您的貢獻!我首先選擇了其他答案,並且是最簡單的解決方案。這看起來更深入,但也會嘗試一下:) – abe 2013-03-20 13:52:06