SQL构建搜索查询以匹配多个ID

时间:2011-05-27 05:03:02

标签: sql

我已经陷入了在表之间寻找常见项目的特殊问题。我必须使用这3张桌子 - 人们可以拥有不止一个家。

我想找到所有与“John Doe”拥有相同住所的人

Persons
    +------+------------------+----------+
    | id   | firsname         | lastname |
    +------+------------------+----------+
    |    1 | John             | Doe      |
    +------+------------------+----------+

Home
+------+------------------+-----------+
| h_id |     address      | year_built|
+------+------------------+-----------+
|    1 | 1233 SQL PL NW   | 1995      | 
+------+------------------+-----------+

Ownership
+-----------+------------------+
| person_id |     house_id     |
+-----------+------------------+
|    1      |         1        |
+-----------+------------------+

我目前对查询应该是什么的想法是我检查Persons.id匹配ownership.id然后找到house.id并将它与两个Person2进行比较。

4 个答案:

答案 0 :(得分:4)

基本上你需要去

persons -> 
    ownership -> 
       ownership that's not John Doe -> 
         back to persons again

这应该这样做

SELECT p2.id,
       p2.first_name,
       p2.last_name
FROM   persons p 
   INNER JOIN ownership o 
     ON p.id = o.person_id 
   INNER JOIN ownership o2 
     ON p.id <> o2.person_id 
        AND o.house_id = o2.house_id 
   INNER JOIN persons p2 
     ON o2.person_id = p2.id 
WHERE p.id = 1

因为dtbarne注意到where子句假设你知道ID。如果要将WHERE子句更改为

WHERE p.first_name = 'John' and p.Last_name = 'Doe'

当然问题在于,如果两个记录共享该名称,您将获得多个结果,因此您希望将House信息添加到SELECT子句以区分

答案 1 :(得分:0)

试试这个:你想找到拥有房子的所有人,房子Id在子查询列表中,这是John Doe拥有的所有房屋。

注意:列名称firsname(sic)与您的问题相符,可能是拼写错误。

select po.*
from Persons po
inner join ownership oo
on po.id = oo.person_id
where house_id in (select house_id 
  from ownership o 
  inner join persons p
  on p.id = o.person_id
  where p.firsname = 'John' and p.lastname = 'Doe'
)

答案 2 :(得分:0)

SELECT Persons.*
FROM Persons, Ownership
WHERE Persons.id = Ownership.person_id
    AND Ownership.house_id = 
        (SELECT Home.h_id
         FROM Home, Persons
         WHERE Home.h_id = Ownership.house_id
            AND Ownership.person_id = id
            AND Persons.firsname = 'John'
            AND Persons.lastname = 'Doe' LIMIT 1);

答案 3 :(得分:0)

SELECT p.*
FROM persons p 
   INNER JOIN ownership o 
     ON p.id = o.person_id  
     INNER JOIN Home h 
     ON o.house_id = h.h_id 
WHERE p.firsname = 'John' and p.lastname = 'Doe'