首页 > 解决方案 > 选择连接中的*每条*记录包含字符串的位置

问题描述

我有以下 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`.`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

标签: mysqlsql

解决方案


您的查询似乎很复杂。怎么样:

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);

推荐阅读