在mySQL中加入三个表?

时间:2012-02-09 19:12:40

标签: php mysql join

我有三张这样的表:

id | name   | location
-----------------------
 1 | ABC    | Location1
 2 | XYZ    | Location2

id | type    | contact
---------------------------
 1 | website | abc.com
 2 | email   | abc@abc.com
 3 | website | xyz.com
 4 | email   | xyz@xyz.com

PersonContact

Person_id | Contact_id
-----------------------
    1     |    1
    1     |    2
    2     |    3
    2     |    4

我希望得到类似的结果:

id | name | website | email
----------------------------------
 1 | ABC  | abc.com | abc@abc.com
 2 | XYZ  | xyz.com | xyz@xyz.com 

3 个答案:

答案 0 :(得分:3)

有几种方法可以做到这一点,但这是一个简单的MySQL

SELECT
   p.id,
   p.name,
   MAX(IF(c.type = 'website', c.contact, NULL)) AS 'website',
   MAX(IF(c.type = 'email', c.contact, NULL)) AS 'email'
FROM
   Person p INNER JOIN
   PersonContact pc ON p.id = pc.Person_ID INNER JOIN
   Contact c ON pc.contact_id = c.id
GROUP BY p.id

答案 1 :(得分:2)

有趣的是,如果不使用if语句,查询会有多复杂。它实际上是每列一个左连接!很棒的工作@Ben!

select p.id, p.name, max(website) as website, max(email) as email from person p
join personContact pc on p.id = pc.person_id
join contact c on pc.contact_id = c.id
left join (
  select c.id as cid, c.contact as website from personContact pc
  join contact c on pc.contact_id = c.id
  where c.type = 'website'
) as WebsiteCol
on c.id = WebsiteCol.cid
left join (
  select c.id as cid, c.contact as email from personContact pc
  join contact c on pc.contact_id = c.id
  where c.type = 'email'
) as EmailCol
on c.id = EmailCol.cid
group by p.id, p.name

答案 2 :(得分:-1)

SELECT p.id, p.name, c.contact FROM Person p, PersonContact pc , Contact c WHERE p.id = pc.Person_id AND pc.Contact_id= c.id