如何从连接的mysql表中选择相同的列值作为不同的列?

时间:2015-06-10 08:47:23

标签: mysql join

我有一个mysql数据库名称为communication的表,其列和值为:

enter image description here

contact表及其列和值为:

enter image description here

从上表中我需要选择以下值:

contact_id f_name l_name phone_number email_address creation_date

其实我不是数据库程序员。你可以问what have you tried so far?。我没有任何想法尝试这个。 每个问题都有解决方案,所以我在这里要求改变数据库设计,也不知道这个愚蠢的想法是不是。 如果有人有解决方案,那将对我有很大的帮助。

注意 :在communication字段的帮助下,email_address和phone_number来自medium表格。并且communication表只能有两个媒介,即MAILPHONEEMAIL是错误的记录,因此EMAIL也是MAIL

由于

3 个答案:

答案 0 :(得分:1)

您必须加入communication两次,具体取决于medium。这应该做的工作(未经测试):

SELECT con.contact_id, con.f_name, con.l_name, com1.value AS phone_number, com2.value AS email_address, con.creation_date
FROM contact con 
LEFT JOIN communication com1 ON com1.contact_id = con.id AND com1.medium = 'PHONE'
LEFT JOIN communication com2 ON com2.contact_id = con.id AND com2.medium LIKE '%MAIL%'

答案 1 :(得分:0)

SELECT CC.contact_id, f_name, l_name, CASE WHEN medium='PHONE' THEN  value ELSE value END 'communication', creation_date
FROM COntact C
JOIN Communication CC on CC.contact_id = C.id
GROUP BY CC.contact_id

......也许,也许不是?

OR 您可以使用medium作为标志加入Communication两次:

SELECT id, f_name, l_name, M.value 'email_address', P.value 'phone_number' ,creation_date
FROM Contact C
JOIN Communication P on P.contact_id = C.id AND medium = 'PHONE'
JOIN Communication M on M.contact_id = C.id AND medium = 'MAIL'
GROUP BY id

答案 2 :(得分:0)

您可以转动表格通讯并将其与联系表

连接
select contact_id,  f_name,  l_name,  phone_number, email_address, creation_date
from contact c 
JOIN (SELECT  contact_id,  
 GROUP_CONCAT(if(Medium= 'MAIL' or Medium= 'EMAIL', value, NULL)) AS 'Email_address', 
 GROUP_CONCAT(if(colID = 'PHONE', value, NULL)) AS 'phone_number'
FROM communication 
GROUP BY contact_id) med
On med.contact_id=c.id;

请注意Medium= 'MAIL' or Medium= 'EMAIL'是电子邮件地址。