Mysql 使用where子句搜索一对多数据库

Mysql 使用where子句搜索一对多数据库,mysql,sql,relational-database,normalization,Mysql,Sql,Relational Database,Normalization,我正在尝试构造一个查询,该查询将允许我使用已定义的属性提取一个人 +----------------------------------------------------+ TABLE: Person +----------------------------------------------------+ owner_id | name 1 | kevin 2 | lee +-------------------------------------------

我正在尝试构造一个查询,该查询将允许我使用已定义的属性提取一个人

+----------------------------------------------------+
TABLE: Person
+----------------------------------------------------+
owner_id | name
1        | kevin
2        | lee

+----------------------------------------------------+
TABLE: Attributes
+----------------------------------------------------+
id              | owner_id       | attributes_id
1               | 1              | 52
2               | 1              | 53
3               | 1              | 23
4               | 2              | 52


SELECT Person.name FROM Person LEFT JOIN `Attributes` ON `Attributes`.`owner_id` = `Person`.`owner_id` WHERE Attributes.attributes_id = 52 AND Attributes.attributes_id = 53;

使用where子句不会返回所有者id 1。如果有人能给我指出正确的方向,我将是最伟大的

您告诉数据库查找同时存在两个不同事物的记录。单个字段不能同时是
52
53
。但是,它可以是一个
或另一个
,因此

... WHERE Attributes.attributes_id = 52 OR Attributes.attributes_id = 53
or more succinctly
... WHERE Attributes.attributes_id IN (52, 53)
问题在于

WHERE Attributes.attributes_id = 52 AND Attributes.attributes_id = 53
换成

WHERE Attributes.attributes_id in (52,53)
我想你想要一个具备你列出的所有特征的人。我把你的左连接改成了内连接,因为不管怎么说它都是有效的。对于所需的每个属性,您都必须分别加入atrributes表

另一种方式是:

SELECT Person.name 
FROM Person 
JOIN `Attributes`  ON `Attributes`.`owner_id` = `Person`.`owner_id` 
WHERE `Attributes`.attributes_id = 52 OR `Attributes`.attributes_id = 53
GROUP BY Person.name 
Having count(*) = 2; 

你好,谢谢你帮我。我尝试了您的查询,数据库返回了两条同名记录。我将selectdistinct放在查询中,它返回一个。在我的情况下,这是SELECT DISTINCT的正确用法吗?
SELECT DISTINCT
只是确保您不会得到任何与其他行重复的行。我发现此解决方案工作得更好,因为in子句将成功,即使单个属性为真。所以这是这个问题的最佳解决方案。非常感谢。
SELECT Person.name 
FROM Person 
JOIN `Attributes`  ON `Attributes`.`owner_id` = `Person`.`owner_id` 
WHERE `Attributes`.attributes_id = 52 OR `Attributes`.attributes_id = 53
GROUP BY Person.name 
Having count(*) = 2;