根据另一个表中的条目选择表中的内容

5
这是设置信息:
表A与表B相连。表B中可能有多个条目(0到n)与表A中的匹配记录相对应。
如何构建一个查询,只有在表B中存在一定数量的匹配记录时才从表A中获取记录?
例如:
表A中有衣服。表B中有衣服的属性。
表B有一个外键指向表A,因此它看起来像这样:
id  fid_clothing1  attributeA
id  fid_clothing1  attributeB
id  fid_clothing1  attributeC
id  fid_clothing2  attributeA
id  fid_clothing2  attributeB

现在,我只想要那些具有属性attributeAattributeBattributeC的衣服。如果我进行OR查询,这不是问题,但我不能只做这样的事情:
SELECT * from tableA
LEFT JOIN tableB on tableB.fid_cloting = tableA.id
WHERE attribute='A' AND attribute='B' AND attribute='C'

这个条件永远不会被满足。我该怎么做?

你应该使用 with 闭包,我认为是这样的。 - Jignesh.Raj
4个回答

2
您可以通过三个内连接来实现...即给我表A中具有所需属性的行。
SELECT A.id FROM tableA A
INNER JOIN tableB BA ON A.id = BA.fid_clothing AND BA.Attribute='A'
INNER JOIN tableB BB ON A.id = BB.fid_clothing AND BB.Attribute='B'
INNER JOIN tableB BC ON A.id = BC.fid_clothing AND BC.Attribute='C'
GROUP BY A.id

2
这个问题的困难在于它泛化能力差(如果你的服装有99个属性怎么办)? - butterchicken

1

我会使用GROUP_CONCAT来获取给定衣物的所有属性的单行数据:

SELECT id,GROUP_CONCAT(attribute order by attribute) as Attributes 
FROM tableB 
GROUP BY id;

给出类似这样的东西:
| id | Attributes |
|  1 | A,B,C      |

从这个结果集中,您可以选择那些连接属性与您要查找的属性集匹配的ID。

从MyConcatenatedResults中选择ID,其中Attributes = 'A,B,C'


有点违背规范化原则,但看起来应该能完成任务。 - pjp

0

可能是这个..得试一下

SELECT * FROM TABLEA a, TABLE b 
WHERE a.id = b.clothing_id 
AND a.id in (SELECT clothing_id from TABLEB where attribute = 'A' AND clothing_id = a.id
UNION select clothing_id from TABLEB where attribute = 'B' AND clothing_id = a.id
UNION select clothing_id from TABLEB where attribute = 'C' AND clothing_id = a.id)

0
另一种方法是使用下面的方式,不需要任何连接,但需要嵌套子查询...已经在一个虚拟数据库上尝试过,看起来很好用。希望能帮到你。
SELECT * 
FROM tableA A 
WHERE id IN ( 
              SELECT clothing_id
              FROM tableB B
              WHERE
                attribute =  "A"
                OR attribute =  "B"
                OR attribute =  "C"
              GROUP BY clothing_id
              HAVING count(*) = 3
            )

1
你需要在 clothing_id 和 attribute 上添加唯一键,以防万一衬衫有两个袖子。 - pjp

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接