mysql - 动态查询取决于多个分组的其他值

时间:2013-02-06 00:50:49

标签: mysql

在我的应用程序中,有一些产品和一个product-variant-group,它们具有一组已定义的属性,该组的产品必须声明这些属性,并且这些属性的组合在该product-variant-group中是唯一的。

来自亚马逊的屏幕示例:

enter image description here

在图像中,第一个选择菜单显然具有所有值。下一个选择菜单取决于先前选择的值,依此类推。

这些已定义的组属性具有为其分配的唯一优先级,在以下派生表中,该属性等于属性本身。

对于给定的属性/优先级以及给定的属性/优先级 - 值对列表。我想检索它可能的值。 值对的优先级必须小于给定的优先级。

public String[] getProductVariantGroupValues(int productVariantGroupId, int priority, Map<Integer, String> prevValues);

一个例子使它更加清晰:

我有一个sql语句,列出了相关产品定义的所有product-variant-group属性:

+---------+----------+-------- +
| product | priority | value   |
+---------+----------+---------+
|       1 |        1 | Black   |
|       1 |        2 | 38      |
|       1 |        3 | Dots    |
|       2 |        1 | Black   |
|       2 |        2 | 38      |
|       2 |        3 | Stripes |
|       3 |        1 | Yellow  |
|       3 |        2 | 40      |
|       3 |        3 | Stripes |
+---------+----------+---------+

Other view for understanding *(priority is arbitrary just for understanding, with this view this would be trivial)*:

+---------+--------+--------+---------+
| product | value1 | value2 | value3  |
+---------+--------+--------+---------+
|       1 | Black  | 38     | Dots    |
|       2 | Black  | 38     | Stripes |
|       3 | Yellow | 40     | Stripes |
+---------+---------------------------+

使用priority = 3调用上述方法,prevValues = {(1, Black), (2, 38)}应生成以下结果数组: {Dots, Stripes}

如果为属性/优先级black选择了1,并且为属性/优先级38选择了2,则属性/优先级{的唯一可能的后续值{1}}为3

该示例已简化,应支持任意数量的属性/优先级。必须动态创建查询以支持任意数量的较低优先级值。

也许我应该使用带有一组固定属性的第二个表appraoch,这将使得唯一约束和此查询变得非常简单。

1 个答案:

答案 0 :(得分:0)

如果我正确理解了这个问题,那么你有一个优先级为1和优先级为2的值,并希望得到所有匹配的优先级为3的值。以下查询获取产品:

select product
from t
group by product
having max(case when priority = 1 and value = 'Black' then 1 else 0 end) = 1 and
       max(case when priority = 2 and value = 40 then 1 else 0 end) = 1

要获得优先级3值要求或聪明的选择语句(假设产品不重复优先级):

select product, max(case when priority = 3 then value end)
from t
group by product
having max(case when priority = 1 and value = 'Black' then 1 else 0 end) = 1 and
       max(case when priority = 2 and value = 40 then 1 else 0 end) = 1

这些查询旨在让您了解如何在代码中构建查询。概括应该非常简单。