如何创建具有多值属性的单个元组?

时间:2012-09-03 01:24:59

标签: mysql

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

我需要的是:

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

mobile_numhome_num存储在supplier_contact表格中。

1 个答案:

答案 0 :(得分:1)

假设您的supplier_contact表有一个'kind'列,您可以加入它两次,每次都指定类型作为连接条件的一部分:

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()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