具有多个表的SQL select语句

时间:2012-10-15 18:18:38

标签: sql

鉴于以下两个表:

Person table 
id (pk) 
first 
middle 
last 
age

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

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

5 个答案:

答案 0 :(得分:28)

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表的所有列。

答案 1 :(得分: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子句中选择不同的列来限制它。

答案 2 :(得分: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'

答案 3 :(得分:1)

首先从人员表中选择所有记录,然后将所有这些记录加入另一个表'地址'...现在你已经记录了所有在地址表中有地址的人...所以最后用邮编过滤你的记录

 select * from Person as P inner join Address as A on 
    P.id = A.person_id Where A.zip='97229'

答案 4 :(得分: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