我有一个复杂的数据库结构,我正在尝试制定一个SQL查询。首先是表格的结构:
Table ANIMALS:
+---------+--------+
| id | name |
+---------+--------+
| 1 | Tiger |
| 2 | Lion |
| 3 | Cat |
+---------+--------+
Table ANIMAL_ATTRIBUTES:
+---------------+-----------+
| attribute_id | animal_id |
+---------------+-----------+
| 10 | 1 |
| 11 | 3 |
| 12 | 3 |
+---------------+-----------+
Table ATTRIBUTE_TEXT:
+--------------+-- ----------+
| attribute_id | value |
+--------------+-------------+
| 10 | black |
| 11 | big |
| 12 | tail |
+--------------+-------------+
Table INFORMATION:
+---------------+-----------+
| attribute_id | filter_id |
+---------------+-----------+
| 10 | 20 |
| 11 | 21 |
| 12 | 22 |
+---------------+-----------+
Table FILTER:
+-----------+-----------------+
| filter_id | name |
+-----------+-----------------+
| 19 | First |
| 20 | Second |
| 21 | Third |
+-----------+-----------------+
需要检查ATTRIBUTE_TEXT.value是否有相应的FILTER.id,并且应该给出具有此值的ANIMAL(其他字段无关紧要)。 到目前为止我得到了这个:
select *
from FILTER as f join INFORMATION as i ON (f.filter_id = i.filter_id)
join ATTRIBUTE_TEXT as at ON (i.attribute_id = at.attribute_id)
join ANIMAL_ATTRIBUTES as aa ON (at.attribute_id = aa.attribute_id)
join ANIMALS as a ON (aa.animal_id = a.id)
where (f.filter_id = 20 and at.value like '%black%');
应该给我'tIGER'作为animal.name。
问题是我有更多的Filter.id来检查相应的ATTRIBUT_TEXT.value: e.g。
Filter 1:
Filter.id = 20 and ATTRIBUTE_TEXT.value = 'black'
and
Filter 2:
Filter.id = 21 and ATTRIBUTE_TEXT.value = 'big'
只有在两者都正确的情况下才会返回“CAT”
答案 0 :(得分:2)
您需要使用OR
并使用适当的parantheses:
select *
from FILTER as f join INFORMATION as i ON (f.filter_id = i.filter_id)
join ATTRIBUTE_TEXT as at ON (i.attribute_id = at.attribute_id)
join ANIMAL_ATTRIBUTES as aa ON (at.attribute_id = aa.attribute_id)
join ANIMALS as a ON (aa.animal_id = a.id)
where
(f.filter_id = 20 and at.value like '%black%')
OR
(f.filter_id = 21 and at.value like '%big%')
答案 1 :(得分:0)
如果你想返回'CAT'并且它必须是'大'和'黑'两者,你应该添加额外的动物属性(INSERT INTO ANIMAL_ATTRIBUTES SELECT 10,3
)并使用如下查询:
select aa.animal_id
from FILTER as f join INFORMATION as i ON (f.filter_id = i.filter_id)
join ATTRIBUTE_TEXT as at ON (i.attribute_id = at.attribute_id)
join ANIMAL_ATTRIBUTES as aa ON (at.attribute_id = aa.attribute_id)
join ANIMALS as a ON (aa.animal_id = a.id)
where
(f.filter_id = 20 and at.value like '%black%')
OR
(f.filter_id = 21 and at.value like '%big%')
GROUP BY aa.animal_id
HAVING count(aa.attribute_id)=2