[英]How can I select same column value as different column from mysql table with join?
I have a table in mysql datbase name as communication
and its columns and values are: 我在mysql datbase名称中有一个表作为communication
,它的列和值是:
and contact
table and its columns and values are: contact
表及其列和值是:
From above tables I have a requirement to select values like following: 从上面的表格中,我需要选择类似以下的值:
contact_id
f_name
l_name
phone_number
email_address
creation_date
contact_id
f_name
l_name
phone_number
email_address
creation_date
Actually I am not a database programmer. 其实我不是数据库程序员。 And you may ask what have you tried so far?
您可能会问what have you tried so far?
. 。 I do not have any idea to try this. 我没有任何尝试的想法。 Every problem has solution so I asked here instead to change database design and also do not know is this stupid idea or not . 每个问题都有解决方案,因此我在这里要求更改数据库设计,也不知道是不是这个愚蠢的主意 。 If anyone have solution it would be great help for me. 如果有人有解决方案,那将对我有很大帮助。
Note : email_address and phone_number comes from communication
table with the help of medium
field. 注意 :email_address和phone_number来自communication
表,并且带有medium
字段。 And communication
table can have only two medium ie MAIL
and PHONE
. 而communication
表只能有两种介质,即MAIL
和PHONE
。 EMAIL
was wrong record so EMAIL
is also MAIL
. EMAIL
是错误的记录,因此EMAIL
也是MAIL
。
Thanks 谢谢
You have to join communication
twice, depending on medium
. 您必须两次加入communication
,具体取决于medium
。 This should do the job (untested): 这应该做的工作(未测试):
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%'
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
... maybe, maybe not? ...也许吧?
OR You could join Communication twice with medium as the flag: 或者,您可以以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
? ?
You can pivot the table communication and join it with contact table 您可以透视表通讯并将其与联系人表合并
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;
Please note Medium= 'MAIL' or Medium= 'EMAIL'
is pivot as email_address. 请注意, Medium= 'MAIL' or Medium= 'EMAIL'
是作为email_address的数据透视。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.