首页 > 解决方案 > MySQL - 子查询或连接多行

问题描述

我的 mysql 查询有点困难。也许有人可以帮助我。

表:

联系人:

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

自定义值:

|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 

多谢你们。

标签: mysqlsql

解决方案


如果你想要额外的rows,那么你的方法很好。但是,我认为您想要额外的,而不是额外的

一种方法是多种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;

推荐阅读