0

我的 MySQL 数据库中有两个表:suppliersupplier_contact. 我可以从这些表中获取数据。如何为每个supplier_IDnot two 生成单个元组或为 single 生成树元组supplier_ID

我需要的是:

-------------------------------------------------------
supplier_id | f_name | l_name | Mobile_num | Home_num |
-------------------------------------------------------

mobile_numhome_num存储在supplier_contact表中。

4

1 回答 1

1

假设您的 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
于 2012-09-03T01:37:05.377 回答