如何查询包含给定多对多关系的所有值的所有行? (不仅仅是其中一个!)

时间:2015-01-08 11:49:51

标签: sqlite relational-division

我遵循数据库结构:

  • 表1:家具(字段:ID)
  • 表2:材料(字段:ID)
  • 表3:MaterialMatching :(字段:ID,FK_Furniture,FK_Material)

这种结构能够将许多材料与每件家具联系起来......

我知道如何查询所有家具,这些家具有一些特殊材料,材料之间的逻辑关系是OR:

select distinct(furniture.ID) from Furniture 
    left join MaterialMatching ON MaterialMatching.FK_Furniture = Furniture.ID
    left join Material On Material.ID = MaterialMatching.FK_Material
    where Material.ID IN (<< material ids I want to query>>)

问题

如何查询所有具有所有材料的家具?我想得到所有家具,材料1和材料2和......

1 个答案:

答案 0 :(得分:0)

这是一个非常脏的解决方案,但它应该解决它。它将归还所有分配给它的材料的家具

select f.* 
from Furniture f
left join (select ftemp.id, count(distinct(mm.FK_Material)) matcount 
           from Furniture ftemp
           left join MaterialMatching mm on mm.FK_Furniture = ftemp.ID
           group by ftemp.id) mmtemp on f.id = mmtemp.id
where mmtemp.matcount = (select count(1) from Material)