我对带有三个表的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发送到必杀技:
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'
有任何想法吗?
谢谢
麦克风
最佳答案
尝试这个:
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;
汤姆·L
关于mysql - MySQL:从三个表中进行选择?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27695993/