mysql - 选择连接中的*每条*记录包含字符串的位置
问题描述
我有以下 MySQL 表:
n_companies:
id 公司名称 1 公司 A 2 B公司
n_contacts:
id company_id 联系人姓名 1 1约翰 2 1 弗兰克 3 2 鲍比 4 2 苏菲
n_custom:
id custom_type custom_type_id 性别 fav_colour 1 触点 1 公红色 2 触点 2 公 红色 3触点3公红 4触点4母绿色
我正在创建一个搜索 UI,它允许人们搜索任何/每个/没有记录包含字符串的位置。
这是我觉得应该为之工作的查询:
查找n_companies
每个联系人 ( n_contacts
) 都是男性的公司 ( )(存储在自定义字段表中n_custom
):
选择 `n_companies`.`id`, `n_companies`.`company_name` 来自`n_companies` 左连接`n_contacts` 开(`n_contacts`.`company_id` = `n_companies`.`id`) 左连接`n_custom`作为`custom_contacts` 开(`n_contacts`.`id` = `custom_contacts`.`custom_type_id` AND `custom_contacts`.`custom_type` = 'contacts' ) 在哪里 存在( 选择`id` 来自`n_custom` WHERE `n_custom`.`custom_type_id` = `n_contacts`.`id` AND `n_custom`.`custom_type` = 'contacts' AND `n_custom`.`gender` LIKE '%male%' ) 不存在( 选择`id` 来自`n_custom` WHERE `n_custom`.`custom_type_id` = `n_contacts`.`id` AND `n_custom`.`custom_type` = 'contacts' AND `n_custom`.`gender` NOT LIKE '%male%' ) 通过...分组 `n_companies`.`id` 订购方式 `n_companies`.`company_name` ASC
我正在寻找上述查询仅返回Company A
,因为它的两个联系人都是男性。 Company B
有1男1女。
笔记:
n_companies
并且c_contacts
是默认使用标准字段创建的表。n_custom
用户可以在其中创建自己的字段来存储有关各种公司相关表的信息。- 我无法在 JOIN 中进行此搜索,因为可能有另一个
OR
独立n_contacts
于上述查询的搜索。
谁能帮我解释为什么我的查询不起作用?
先感谢您。
编辑 我刚刚意识到我的“否”记录也不起作用。在我看来,这应该返回零行,但它不会:
选择 `n_companies`.`id`, `n_companies`.`company_name` 来自`n_companies` 左连接`n_contacts` 开(`n_contacts`.`company_id` = `n_companies`.`id`) 左连接`n_custom`作为`custom_contacts` 开(`n_contacts`.`id` = `custom_contacts`.`custom_type_id` AND `custom_contacts`.`custom_type` = 'contacts' ) 在哪里 不存在 ( 选择`id` 来自`n_custom` WHERE `n_custom`.`custom_type_id` = `n_contacts`.`id` AND `n_custom`.`custom_type` = 'contacts' AND `n_custom`.`fav_colour` NOT LIKE '%red%' ) 通过...分组 `n_companies`.`id` 订购方式 `n_companies`.`company_name` ASC
解决方案
您的查询似乎很复杂。怎么样:
SELECT c.id, c.company_name
FROM n_companies c LEFT JOIN
n_contacts co
ON co.company_id = c.id LEFT JOIN
n_custom cu
ON co.id = cu.custom_type_id AND
cu.custom_type = 'contacts'
GROUP BY c.id, c.company_name
HAVING MIN(cu.gender) = 'male' AND MIN(cu.gender) = MAX(cu.gender);
推荐阅读
- python - Python 3.7 真的比 python 3.6 快吗?
- azure - 在 Powershell 中找不到属性“StrongAuthenticationUserDetails”
- angular - 仅当Angular中的值> 0时如何在视图中显示数据
- c - 如何在 C 中将客户端的 IP 存储在数组中(套接字编程)
- java - 如何连接用户输入的下两个字符并打印它们?
- javascript - 如何正确分配标头以在 Javascript 中获取请求
- rust - 如何指定生命周期以使本地引用的值与传入的引用不同?
- c++ - proto c++ 实现 - “标记为‘覆盖’,但不覆盖”错误
- java - 用 Java 编写的 UDF 的全局变量如何在 Cloudera Impala 中起作用?
- linux - `sudo` with command substitution