我有2张桌子:
表objects:
objects
object_id | object_group_id
表attributes:
attributes
attr_id | attr_object_id | attr_property_id | attr_value
现在,我想获取所有object_id位置object_group_id = 1并过滤两个属性:
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'
…但是仍然无法得到我所需要的。
经过几个小时的合并和尝试,我终于做到了:
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。
INNER JOIN