过滤具有多个条件的EAV表

时间:2015-10-29 19:03:07

标签: mysql sql entity-attribute-value

我有两张桌子:

objects

object_id | object_group_id

attributes

attr_id | attr_object_id | attr_property_id | attr_value

现在,我希望将所有object_id放在object_group_id = 1,并过滤两个属性:

(attr_property_id = 1 AND attr_value <= '100000')
   AND 
(attr_property_id = 2 AND attr_value > '2000')

我试图构建一些查询,如下所示:

SELECT * FROM objects as o

/* filter1 join */
INNER JOIN 
    attributes AS f1 
        ON 
    o.object_id = f1.attr_object_id 
        AND 
    f1.attr_property_id = 1

/* filter2 join */
INNER JOIN 
    attributes AS f2 
        ON 
    f1.attr_object_id = f2.attr_object_id 
        AND 
    f2.attr_property_id = 2

WHERE 
    o.object_group_id = 1
       AND
   f1.attr_value <= '100000'
       AND
   f2.attr_value > '2000'

......但仍然无法得到我需要的东西。

2 个答案:

答案 0 :(得分:3)

经过几个小时的结合和尝试,我终于做到了:

    SELECT * FROM objects as o

/* filter1 join */
INNER JOIN 
    attributes AS f1 
        ON 
    o.object_id = f1.attr_object_id 
        AND 
    f1.attr_property_id = 1
        AND
    f1.attr_value <= '100000'

/* filter2 join */
INNER JOIN 
    attributes AS f2 
        ON 
    f1.attr_object_id = f2.attr_object_id 
        AND 
    f2.attr_property_id = 2
        AND
    f2.attr_value > '2000'

WHERE 
    o.object_group_id = 1

我太近了,通过将所有过滤条件移到INNER JOIN来完成此操作。

答案 1 :(得分:0)

试试这个。我不知道为什么你有最后一行

SELECT
  o.object_id, o.object_group_id,
  f1.attr_value AS val1,
  f2.attr_value AS val2,
FROM objects AS o
LEFT JOIN attributes f1 ON o.object_id = f1.attr_object_id AND f1.attr_property_id = 1
LEFT JOIN attributes f1 ON o.object_id = f2.attr_object_id AND f2.attr_property_id = 2
WHERE
    o.object_group_id = 1
AND
   f1.attr_value <= '100000'
AND
   f2.attr_value > '2000';

删除此行并进行测试

AND
   f1.attr_value <= '100000'
AND
   f2.attr_value > '2000';