mysql - 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
多谢你们。
解决方案
如果你想要额外的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;
推荐阅读
- ios - iOS Swift inApp 购买与 Auto-Renewable 一个订阅与多个设备
- ios - 为什么我无法获取 UIStatusBarSignalStrengthItemView?
- android - 在已删除通知倾斜的应用中获取重复通知
- azure - Outlook 推送通知 REST API - 如何保护通知 URL?
- php - 会话超时时的drupal 7重定向
- .net - 在 SaxonEE/dotNet 中针对 xsd 验证 xml 时;如何调用 SetInvalidityHandler?
- flutter - 如何在颤动中更改 textField 的下划线颜色?
- ios - Cordova 媒体插件 ios“无法使用 AVAudioRecorder 代码开始录制:1”
- javascript - 地图搜索在数组内做出反应
- c++ - MSVC 2008,调试过程,无法调试