SQL查询:数组在数组中

时间:2015-06-07 21:37:10

标签: sql arrays filtering

我在数据库中有样本数据:

id (int)   name (varchar)           parts (varchar)
1          some_element             wheel, bearing, hinge, servo
2          another_element          bearing, servo, lift
3          third_element            motor, wire

我想按部分过滤结果。例如: 我正在输入 wheel,servo - 没有结果

我正在输入滚轮,方位,伺服,铰链 - 返回 some_element 记录

我正在输入轴承,伺服,升降,车轮,轴承,铰链 - 它会返回 some_element another_element

如何构建SQL查询?零件领域是否有更好的其他数据类型?

1 个答案:

答案 0 :(得分:1)

进行一些规范化,以便您可以更轻松地编写查询,并且不会出现此类异常。

你需要另一种结构,比如:

element

+----+---------------+
| id | name          |
+----+---------------+
|  1 | some_element  |
+----+---------------+
|  2 | another_elem  |
+----+---------------+
|  3 | third_elem    |
+----+---------------+

part

+----+----------+
| id | name     |
+----+----------+
|  1 | wheel    |
+----+----------+
|  2 | bearing  |
+----+----------+
|  3 | hinge    |
+----+----------+
|  4 | servo    |
+----+----------+
 etc..

另一个,例如element_parts以m:n关系连接其他两个

+----+---------+---------+
| id | elem_id | part_id |
+----+----------+--------+
|  1 | 1       | 1       |
+----+---------+---------+
|  2 | 1       | 2       |
+----+---------+---------+
|  3 | 1       | 3       |
+----+---------+---------+
|  4 | 2       | 3       |
+----+---------+---------+
|  5 | 2       | 4       |
+----+---------+---------+
 etc..

现在,您可以编写一个查询,例如,过滤包含(或需要)wheelservo的元素(调整this问题的已接受答案):

select *
from element e
where 2 = (
    select count(distinct p.id)
    from element_parts ep
    inner join part p on p.id = ep.part_id
    where p.name in ('wheel', 'servo') 
    and ep.elem_id = e.id
);