0

mySQL 查询 - 我有一个表 'database'.'table_product_options' 包含大约 1000 行。此表应包含每个“product_id”的 4x 行 - 分配给每个“customer_group”的相同产品(如下图所示)。这应该相当于每个 customer_group 约 250 行。

但是,我在每个'customer_group'上运行了一个 COUNT ,发现组a + c有一些缺失的条目(组b + d 总共 250 行,但组a + c只有 245 行)。

+----------------+----------------+
| 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 查询(或替代查询)以显示分配了少于 4 行的“product_id” ?或者,换句话说,我怎样才能找到丢失的条目?

我尝试了许多不同的查询,包括 SELECTs 与 WHERE NOT EXIST 等相结合,但我的想法已经不多了。我已经修改了十几个 stackoverflow 答案,但没有一个非常合适,并且无法修改语法以使其正常工作。

任何帮助将不胜感激(因为我预计将来会再次出现同样的问题......)。我可能最终会用眼睛擦桌子!

4

2 回答 2

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

您可能必须逐行切换拥有和分组。我把订单弄糊涂了。

于 2013-03-20T12:15:16.073 回答
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
于 2013-03-20T12:30:31.257 回答