我正在尝试编写一个SQL查询来返回采用猫贝壳的人的姓名'
我有一张adopters
表,其中包含将要或已经采用动物的人。
pets=# SELECT * FROM adopters;
id | first_name | last_name | address | phone_number
----+------------+-----------+----------------------+--------------
1 | jack | smith | 1 ave | 123-123-1234
2 | james | dude | 2 ave | 221-234-4444
3 | Forrest | Stone | 3 lane | 234-667-6543
4 | craig | list | 44 bulvard | 555-444-3243
5 | kap | seven | no team | 999-000-0909
6 | Miles | Garrett | First energy stadium | 123-555-2424
(6 rows)
cats
表,其中包含猫
pets=# SELECT * FROM cats;
id | name | gender | age | intake_date | adoption_date
----+----------+--------+-----+---------------------+---------------------
1 | Mushi | M | 1 | 2016-01-09 00:00:00 | 2016-03-22 00:00:00
2 | Seashell | F | 7 | 2016-01-09 00:00:00 |
3 | Azul | M | 3 | 2016-01-11 00:00:00 | 2016-04-17 00:00:00
4 | Victoire | M | 7 | 2016-01-11 00:00:00 | 2016-09-01 00:00:00
5 | Nala | F | 1 | 2016-01-12 00:00:00 |
(5 rows)
还有一张adoptions
表,其中记录了所有已采用的记录。
pets=# SELECT * FROM adoptions;
id | adopters | cat | dog | fee | date
----+----------+-----+-------+-------+------------
1 | 1 | | 10001 | 10.50 | 2017-11-22
2 | 2 | | 10007 | 10.50 | 2017-11-22
3 | 3 | 5 | | 10.50 | 2017-11-22
4 | 5 | 2 | | 10.50 | 2016-11-22
(4 rows)
我在加入三张桌子时遇到了麻烦,即使你没有直接回答这个问题,我也非常感谢你指出一个有用的资源方向。
答案 0 :(得分:2)
这应该有效:
SELECT p.first_name, p.last_name
FROM adoptions a
JOIN cats c on c.id = a.cat
JOIN adopters p on p.id = a.adopters
WHERE c.name = 'seashell'
答案 1 :(得分:0)
试试这个
SELECT adopters.first_name, adopters.last_name
FROM adopters
INNER JOIN adoptions on adopters.id = adoptions.adopters
INNER JOIN cats on cats.id = adoptions.cats
WHERE cats.id = 2
答案 2 :(得分:0)
TRY:
SELECT
pers.first_name,
pers.last_name
FROM
cats ct
JOIN
adoptions adop ON (ct.id = adop.id)
JOIN
adopters pers ON (adop.adopters = pers.id)
WHERE
ct.name = "Seashell ";
答案 3 :(得分:0)
SELECT a.first_name, a.last_name
FROM adopters a, cats c, adoptions ad
WHERE a.id = ad.adopters AND ad.cat = c.id
AND c.name = "Seashell";
请尝试这个