过滤一对多关系查询结果的最佳方法。 MySQL的

时间:2013-09-02 02:54:53

标签: mysql join query-optimization inner-join one-to-many

使用多个连接是一个好主意,通过多个属性值过滤查询结果?例如:

product
--------
pid desc 
--------
1   prod1
2   prod2

attrib
--------
pid  aid val
--------
1    1   "avalue1"
1    2   "avalue2"

查询:

SELECT p.* FROM product p
INNER JOIN attrib a1 ON (p.pid=a1.pid)
INNER JOIN attrib a2 (p.pid=a2.pid)
WHERE a1.aid=1 and a1.val="avalue1" and a2.aid=2 and a2.val="avalue2"

或者有更好的方法可以做到这一点?感谢。

1 个答案:

答案 0 :(得分:3)

join方法肯定有效,它可以利用索引。但是,我更喜欢使用having进行聚合,因为它更灵活:

select p.*
from product p join
     attrib a
     on p.pid = a.pid
group by p.pid
having sum(a.aid = 1 and a.val = 'avalue1') > 0 and
       sum(a.aid = 2 and a.val = 'avalue2') > 0;

having子句中的每个条件都计算满足其中一个条件的属性数。很容易添加另一个条件,正面或负面。例如,修改上述要求缺少3 / avalue3:

select p.*
from product p join
     attrib a
     on p.pid = a.pid
group by p.pid
having sum(a.aid = 1 and a.val = 'avalue1') > 0 and
       sum(a.aid = 2 and a.val = 'avalue2') > 0 and
       sum(a.aid = 3 and a.val = 'avalue3') = 0;