我有一个复杂的数据库结构,我正在尝试为其制定一个 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%');
这应该给我作为animal.name的'TIGER'。
问题是我有更多 Filter.id 要检查相应的 ATTRIBUT_TEXT.value:例如
Filter 1:
Filter.id = 20 and ATTRIBUTE_TEXT.value = 'black'
and
Filter 2:
Filter.id = 21 and ATTRIBUTE_TEXT.value = 'big'
如果两者都正确,则仅应返回结果“CAT”