MySQL表中的垂直数据选择

时间:2014-10-23 05:43:03

标签: php mysql entity-attribute-value

如果我有这样的表:

ID color size weight
1  red   2    3
2  green 4    5

因此,要运行mysql查询以查找IDcolor:red以及size:2weight:3的{​​{1}}号码,我可以执行此操作:

select ID from table where color=red AND size=2 AND weight=3

随着属性的增加,除了颜色,重量,大小,里程,速度等......我想保持表缩放,以这种方式组织它是有意义的

ID  ID2  property  value
1   1    color     red
2   1    size      2
3   1    weight    3
4   2    color     green
5   2    size      4
6   2    weight    5

如何在此处运行选择查询,以查找IDcolor:red以及size:2

weight:3号码

我应该创建一堆像这里建议的自连接:

select t.id2 
from test t
join test t1 on(t.id = t1.ID2)
join test t2 on(t.id = t2.ID2)
where t.property = 'color'
and t1.property = 'size'
and t2.property = 'weight'
and t.value = 'red'
and t1.value = '2'
and t2.value = '3'

或者我应该从数据库中获取所有ID2并使用PHP进行排序?

或者还有其他方法可以从表中选择数据吗?

我正在查看10,000个ID和大约200个属性,这些属性的数量将会非常缓慢地增长。

2 个答案:

答案 0 :(得分:1)

如果您不打算使用一堆自连接,这是获得所需结果集的另一种方法,那么您可以使用in(),count(distinct) and group by并且我假设每个id2您具有唯一属性

select t.id2 
from test t
where t.property in('color','size','weight')
and t.value in('red','2','3')
group by t.id2 
having count(distinct t.property) = 3

以上查询将查找提供值的property列,并且使用distinct = 3部分计数将确保所有提供的键/值对匹配,因此,如果您的属性从3增长,那么您必须提供没有。这将等于没有。要匹配的属性,即案例t.property in('color','size','weight','test'),计数部分将更改为having count(distinct t.property) = 4

DEMO

答案 1 :(得分:0)

我不确定我明白你想做什么,但我会试一试。

作为一般规则:永远不要从数据库中获取您不需要的数据。不要选择超出需要的数量,并在代码中丢弃结果。

似乎有意义(根据我的理解)是将您的表拆分为2.一个指定您的项目,一个指定其属性:

项目表(项目)

ID name
1  item 1
2  item 2

道具表(道具)

itemID name  value
1       color red
1       size  2
2       color blue
2       size  3

要获取大小为2的所有蓝色项目,您可以运行以下表单的查询:

Select name
  from items
  join props as colors on items.id = colors.itemId
  join props as sizes on items.id = sizes.itemId
  where (colors.name = 'color' and colors.value = 'blue')
    and (sizes.name = 'size' and sizes.value = '2')