0

我有一个复杂的数据库结构,我正在尝试为其制定一个 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”

4

2 回答 2

2

您需要使用OR适当的括号:

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%')
于 2013-02-06T09:32:53.513 回答
0

如果您希望返回 'CAT' 并且它必须是 'big' 和 'black' 两者,则应添加额外的动物属性 ( 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
于 2013-02-06T09:50:12.563 回答