Mysql 根据其他表中的条目从表中选择

Mysql 根据其他表中的条目从表中选择,mysql,Mysql,以下是设置: 表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 f

以下是设置:

表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
现在,我只想要属性为attributeA、attributeB和attributeC的衣服。如果我执行或查询,这不是问题,但我不能只执行以下操作:

SELECT * from tableA
LEFT JOIN tableB on tableB.fid_cloting = tableA.id
WHERE attribute='A' AND attribute='B' AND attribute='C'
| id | Attributes |
|  1 | A,B,C      |

此条件的计算结果永远不会为真。我该怎么做呢?

你可以用3个内部连接来完成。。。i、 e.给我一个表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

也许是这个。。我必须试一试

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)

另一种方法是如下所示,这需要零联接,但需要一个嵌套的子查询。。。have在一个虚拟数据库上尝试了这个方法,它似乎完成了任务。希望能有帮助

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 ) 我将用于获取给定衣服的所有属性的一行:

SELECT id,GROUP_CONCAT(attribute order by attribute) as Attributes 
FROM tableB 
GROUP BY id;
给出类似于:

SELECT * from tableA
LEFT JOIN tableB on tableB.fid_cloting = tableA.id
WHERE attribute='A' AND attribute='B' AND attribute='C'
| id | Attributes |
|  1 | A,B,C      |
从这个结果集中,您可以选择那些连接属性与您要查找的属性集相匹配的ID


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

您希望在id上添加唯一的键,属性只是在一件衬衫有两个slevest的情况下,这个问题是它不能很好地概括,如果你的衣服有99个属性怎么办?有点违背正常化原则,但看起来应该这样做。你应该和clouse一起使用我想是的