Mysql一对多连接,行到列

时间:2017-07-09 15:10:42

标签: mysql join one-to-many

我在MySql数据库中有2个名为 con01_objects con01_object_contacts 的表。它们有外键,如图所示(con01_objects.id = con01_object_contacts.obj_id)。

image

如您所见, con01_object_contacts 表包含 contact_type 列,该列将包含一个对象及其相应联系人的多种联系类型(联系类型:0号,1-web) ,2-tolfree,3-facebook,4-twitter,5-instagram,6-youtube,7-mail)。

我需要的是加入这两个表,这样就不会有重复的对象。我需要一个连接结果,它会将每个联系人类型显示为一列。如果对应的联系人类型中的对象没有联系人,则该条目应为NULL。

+++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++

对象--- contype_0(num)---- contype1(WEB)----- contype(tolfree) ++++++++++++++++++++++++++++++++++++++++++++++++++ +++++++++++++

obj1 ---- +96785445578700 ---- SOMETHING.c0M ----- 45469889

obj2 ---- +55457875748787 ------ NULL --------------------- 42499898

我尝试了这个查询,但它返回重复的行,因为一个对象有不同的联系类型。

SELECT * FROM con01_objects LEFT JOIN con01_object_contacts ON con01_objects.id = con01_object_contacts.obj_id

事先谢谢。

1 个答案:

答案 0 :(得分:0)

我认为你正在寻找这个:

Select distinct(a.jid), 
(SELECT contact FROM con01_object_contacts where contact_type = '0') as contype_0, 
(SELECT contact FROM con01_object_contacts where contact_type = '1') as contype_1,
(SELECT contact FROM con01_object_contacts where contact_type = '2') as contype_2
from con01_objects a
left join con01_object_contacts as b
on a.id = b.obj_id;