假设您的 supplier_contact 表有一个“种类”列,您可以将其连接两次,每次都将类型指定为连接条件的一部分:
SELECT s.supplier_id, s.f_name, s.l_name,
cmob.number as Mobile_num,
chom.number as Home_num
FROM
suppliers AS s
LEFT JOIN supplier_contact AS cmob ON s.supplier_id = cmob.supplier_id AND cmob.type = 'mobile'
LEFT JOIN supplier_contact AS chom ON s.supplier_id = chom.supplier_id AND chom.type = 'home'
GROUP BY supplier_id
请注意,MySQL 允许这样做,但在其他 RDBMS 中,您需要在数字列的 SELECT 列表中使用聚合函数,例如MAX()
or GROUP_CONCAT()
。
或者,您可以执行单个联接并将条件添加到 SELECT 列表:
SELECT s.supplier_id, s.f_name, s.l_name,
GROUP_CONCAT(IF(c.type = 'mobile', c.number, NULL)) AS Mobile_num,
GROUP_CONCAT(IF(c.type = 'home', c.number, NULL)) AS Home_num
FROM
suppliers AS s
LEFT JOIN supplier_contact AS c USING(supplier_id)
GROUP BY supplier_id