使用where子句搜索一个到多个数据库

时间:2012-07-16 18:59:56

标签: mysql sql relational-database normalization

我正在尝试构建一个允许我拉出具有已定义属性的人的查询。

+----------------------------------------------------+
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子句没有返回owner_id 1.如果有人能指出我正确的方向,我会非常感激!

3 个答案:

答案 0 :(得分:3)

您告诉数据库要同时查找两个不同内容的记录。单个字段不能同时同时同时为5253。但是,它可以是另一个OR,所以......

... WHERE Attributes.attributes_id = 52 OR Attributes.attributes_id = 53
or more succinctly
... WHERE Attributes.attributes_id IN (52, 53)

答案 1 :(得分:3)

问题在于

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

将其更改为

WHERE Attributes.attributes_id in (52,53)

答案 2 :(得分:1)

SELECT Person.name 
FROM Person 
JOIN `Attributes` A1 ON A1.`owner_id` = `Person`.`owner_id` 
JOIN `Attributes` A2 ON A2.`owner_id` = `Person`.`owner_id` 
WHERE A1.attributes_id = 52 AND A2.attributes_id = 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;