14

给定以下两个表:

Person table 
id (pk) 
first 
middle 
last 
age

Address table 
id(pk) 
person_id (fk person.id) 
street 
city 
state 
zip

如何创建返回邮政编码为 97229 的人员的所有信息的 SQL 语句?

4

5 回答 5

39
Select * from people p, address a where  p.id = a.person_id and a.zip='97229';

或者您必须尝试使用JOIN​​哪种方法更有效、更好,因为 Gordon Linoff 在下面的评论中还说您需要学习这一点。

SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299';

p.*意味着它将显示 PERSONS 表的所有列。

于 2012-10-15T18:21:34.860 回答
4

您需要连接两个表:

select p.id, p.first, p.middle, p.last, p.age,
       a.id as address_id, a.street, a.city, a.state, a.zip
from Person p inner join Address a on p.id = a.person_id
where a.zip = '97229';

这将从两个表中选择所有列。select您当然可以通过在子句中选择不同的列来限制它。

于 2012-10-15T18:21:02.093 回答
1

像那样:

SELECT p.*, a.street, a.city FROM persons AS p
JOIN address AS a ON p.id = a.person_id
WHERE a.zip = '97299'
于 2012-10-15T18:20:51.850 回答
1

首先从人员表中选择所有记录,然后将所有这些记录与另一个表“地址”连接起来……现在你已经记录了所有在地址表中有地址的人……所以最后按邮政编码过滤你的记录。

 select * from Person as P inner join Address as A on 
    P.id = A.person_id Where A.zip='97229'
于 2012-10-15T18:52:30.280 回答
0
select P.*,
A.Street,
A.City,
A.State
from Preson P
inner join Address A on P.id=A.Person_id
where A.Zip=97229
Order by A.Street,A.City,A.State
于 2013-03-20T14:44:01.050 回答