MySQL:从三个表中选择?

时间:2014-12-29 21:05:27

标签: mysql

我在使用三个表的MySQL查询时遇到问题。我想搜索一个名字并获得所有(甚至更好的第一个)电话号码和电子邮件。这是我的表格:

Table 1, contact
==========
id | name
==========
1  | stefan
2  | michael
3  | andy
4  | bob

Table 2, phone
==============================
id | contact_id | phonenumber
==============================
1  | 1          | +1 434 434232
2  | 1          | +1 434 24234
3  | 2          | +1 89234
4  | 4          | +1 345345
5  | 4          | +1 434 7567567

Table 3, email
===============================
id | contact_id | emailaddress
===============================
1  | 1          | stefan@home.com
2  | 1          | stefan@work.com
3  | 1          | stefan@mars.com
4  | 4          | bob@anywhere.com
5  | 2          | michael@nothing.com

这是我的查询,它将MySQL发送到nirvana:

SELECT c.name, p.phonenumber, e.emailaddress
FROM contact AS c
JOIN phonenumber AS p ON c.id = p.contact_id
JOIN email AS e ON c.id = e.contact_id
WHERE c.name = 'michael'

当我只进行一次加入时,这可以正常工作:

SELECT c.name, p.phonenumber
FROM contact AS c
JOIN phonenumber AS p ON c.id = p.contact_id
WHERE c.name = 'michael'

有什么想法吗?

由于

麦克

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT c.name, p.phonenumber, e.emailaddress
FROM name_of_your_schema.contact AS c
JOIN name_of_your_schema.phone AS p ON c.id = p.contact_id
JOIN name_of_your_schema.email AS e ON c.id = e.contact_id
WHERE c.name = 'stefan'
LIMIT 1;

Tom L。

答案 1 :(得分:0)

尝试

SELECT c.name, p.phonenumber, e.emailaddress
FROM contact c
INNER JOIN phone p ON c.id = p.contact_id
INNER JOIN email e ON p.contact_id = e.contact_id
WHERE c.name = 'michael'

答案 2 :(得分:0)

要为每个联系人获得一个结果,您可能会以一种非正统的方式使用聚合。我修改了@Emanuel Saringan的查询:

SELECT c.name, min(p.phonenumber), min(e.emailaddress)
FROM contact c
left JOIN phone p ON c.id = p.contact_id
left JOIN emailaddress e ON c.id = e.contact_id
WHERE c.name = 'michael'
GROUP BY c.id

在这里看到它的工作: http://sqlfiddle.com/#!2/6a8700/2