我正试图从几个表中获取多个属性(例如卧室,浴室等)是的,我似乎只能使用当前查询获得一个属性。我错过了什么?
我最终想要找到的是property_id,有2间浴室和2间卧室。在这种情况下,我想要的结果是属性id 1和4。
以下是sqlfiddle
上的示例示例表:
property
--------
id
1
2
3
4
attribute
---------
id name
1 bedrooms
2 bathrooms
attribute_value
---------------------
id attribute_id value
1 1 1
2 1 2
3 1 3
4 2 1
5 2 2
6 2 3
property_attributes
------------------------------
property_id attribute_value_id
1 2
1 5
2 2
2 4
3 1
3 4
4 2
4 5
如果我只想查看基于单个属性的查询,那么此查询可以生成我想要的结果:
SELECT p.property_id
FROM property p
INNER JOIN property_attribute pa ON p.property_id = pa.property_id
INNER JOIN property_area pc ON p.property_id = pc.property_id
WHERE pa.attribute_value_id
IN (
SELECT av.attribute_value_id
FROM attribute_value av
INNER JOIN attribute a ON av.attribute_id = a.attribute_id
WHERE a.name like 'bedrooms' AND av.value like '2')
但是我必须做些什么来获得具有更多属性的结果(例如WHERE a.name如'bathroom'和av.value like'2')?如果我在main where子句中添加另一个子查询,则不会返回任何结果。
/// 编辑 ///
如果有其他人在这种情况下结束,这里的解决方案对我有用:
SELECT p.property_id
FROM property p
INNER JOIN property_attribute pa ON p.property_id = pa.property_id
INNER JOIN property_attribute pa2 ON p.property_id = pa2.property_id
INNER JOIN property_attribute pa3 ON p.property_id = pa3.property_id
WHERE pa.attribute_value_id = 2
AND pa2.attribute_value_id = 5
AND pa3.attribute_value_id = 7
这样可以使用自我加入。
答案 0 :(得分:3)
你的架构中有很多间接。你需要property_attribute
表有什么特别的意义吗?您是否希望许多属性共享单个属性值?
无论如何,这是您的查询。非常符合我上面提到的两个possible duplicates的精神。
SELECT property.property_id,
bedrooms.value AS bedrooms,
bathrooms.value AS bathrooms
FROM property,
attribute AS bedrooms_attr,
attribute_value AS bedrooms,
property_attribute AS bedrooms_prop,
attribute AS bathrooms_attr,
attribute_value AS bathrooms,
property_attribute AS bathrooms_prop
WHERE bedrooms_attr.name = 'bedrooms'
AND bedrooms.attribute_id = bedrooms_attr.attribute_id
AND bedrooms.attribute_value_id = bedrooms_prop.attribute_value_id
AND bedrooms_prop.property_id = property.property_id
AND bedrooms.value = 2
AND bathrooms_attr.name = 'bathrooms'
AND bathrooms.attribute_id = bathrooms_attr.attribute_id
AND bathrooms.attribute_value_id = bathrooms_prop.attribute_value_id
AND bathrooms_prop.property_id = property.property_id
AND bathrooms.value = 2
感谢您向play with提供数据。