MySQL-子查询或联接多行

时间:2020-01-21 12:45:28

标签: mysql sql

我的mysql查询有点麻烦。也许有人可以帮助我。

表格:

联系人:

|id|phone|first_name|last_name|email|company|

custom_values:

|id|c_id|custom_field_id|value|

表custom_values具有不同的custom_field_ids

id 4 = mobile
id 5 = fax
id 20 = 2nd phonenumber

当前查询为我提供了联系人表中的所有信息。

concat(contacts.first_name, ' ', contacts.last_name, ' - ', contacts.company) as displayname,     contacts.phone, contacts.last_name, contacts.first_name, contacts.company, contacts.email
from contacts

现在,我想将custom_values表中的信息添加到上面的查询中。 是否可以添加3行,从而为每个联系人增加手机,传真和第二个电话号码?

我尝试了下一个查询,但这没用。

SELECT 
    concat(contacts.first_name, ' ', contacts.last_name, ' - ', contacts.company) as displayname, contacts.phone, contacts.last_name, contacts.first_name, contacts.company, contacts.email,custom_values.value as mobile 
from custom_values 
join contacts on custom_values.customized_id = contacts.id 
where custom_values.custom_field_id=4 

谢谢大家。

1 个答案:

答案 0 :(得分:1)

如果您想要其他,那么您的方法很好。但是,我认为您需要附加的,而不是附加的

一种方法是多个LEFT JOIN

select concat(c.first_name, ' ', c.last_name, ' - ', c.company) as displayname,
       c.phone, c.last_name, c.first_name, c.company, c.email, 
       cvm.value as mobile, 
       cvf.value as fax, 
       cvp2.value as second_phone 
from contacts c left join
     custom_values cvm
     on cvm.customized_id = c.id and
        cvm.custom_field_id = 4 left join
     custom_values cvf
     on cvf.customized_id = c.id and
        cvf.custom_field_id = 5 left join
     custom_values cvp2
     on cvp2.customized_id = c.id and
        cvp2.custom_field_id = 20;