0

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

+----------------------------------------------------+
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。如果有人能指出我正确的方向,我会非常感激!

4

3 回答 3

3

问题在于

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

将其更改为

WHERE Attributes.attributes_id in (52,53)
于 2012-07-16T19:02:47.763 回答
3

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

... WHERE Attributes.attributes_id = 52 OR Attributes.attributes_id = 53
or more succinctly
... WHERE Attributes.attributes_id IN (52, 53)
于 2012-07-16T19:02:08.717 回答
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; 

我假设您想要一个具有您列出的所有属性的人。我将您的左连接更改为内部连接,因为无论如何它都是有效的。您必须为所需的每个属性分别加入属性表。

另一种方法是:

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; 
于 2012-07-16T19:09:26.823 回答