0

使用多个连接是按多个属性值过滤查询结果的好主意吗?例如:

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"

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

4

1 回答 1

3

join方法绝对有效,并且可以利用索引。但是,我更喜欢聚合 withhaving因为它更灵活:

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;
于 2013-09-02T03:06:57.827 回答