MySQL获取所有关联记录,其中至少一条记录与查询匹配

时间:2018-07-11 16:44:28

标签: mysql sql

我正在尝试使此MySQL搜索查询正常工作。我希望它返回firstName,lastName,email或至少一个secondaryEmail匹配搜索字符串的所有用户。一个用户可以拥有许多辅助电子邮件。

这是我的SQL查询:

SELECT `users`.`id`,
       `users`.`first_name` AS `firstName`,
       `users`.`last_name` AS `lastName`,
       `users`.`email`,
       `usersSecondaryEmails`.`id` AS `usersSecondaryEmails.id`,
       `usersSecondaryEmails`.`email` AS `usersSecondaryEmails.email`
FROM `Users` AS `users`
LEFT OUTER JOIN `UsersSecondaryEmails` AS `usersSecondaryEmails`
        ON `users`.`id` = `usersSecondaryEmails`.`user_id`
WHERE (`users`.`first_name` LIKE '%bob%'
        OR `users`.`last_name` LIKE '%bob%'
        OR `users`.`email` LIKE '%bob%'
        OR `usersSecondaryEmails`.`email` LIKE '%bob%');

此查询成功返回,但是,当只有匹配的辅助电子邮件时,它仅返回该电子邮件,而不是所有关联的电子邮件。如果找到至少一个辅助电子邮件,如何更改此查询以返回所有电子邮件?我知道它很可能会在其中包含EXISTS的子查询,但是我不太确定该放在哪里。

编辑:“用户”表具有名字,姓氏和电子邮件 UsersSecondaryEmails表具有user_id和电子邮件

如果用户有2个辅助电子邮件(在UsersSecondaryEmails上的“电子邮件”列),并且其中至少有一个与搜索字符串匹配,则我希望得到所有他们的辅助电子邮件。截至目前,此操作仅返回匹配的电子邮件。

3 个答案:

答案 0 :(得分:2)

子查询应该执行

 SELECT 
       `users`.`id`,
       `users`.`first_name` AS `firstName`,
       `users`.`last_name` AS `lastName`,
       `users`.`email`,
       `usersSecondaryEmails`.`id` AS `usersSecondaryEmails.id`,
       `usersSecondaryEmails`.`email` AS `usersSecondaryEmails.email`
    FROM users users, UsersSecondaryEmails usersSecondaryEmails
    WHERE users.id IN (SELECT user_id FROM UsersSecondaryEmails)
    AND users.id = usersSecondaryEmails.user_id

    AND
    (
    `users`.`first_name` LIKE '%bob%'
    OR
    `users`.`last_name` LIKE '%bob%'
    OR
    `users`.`email` LIKE '%bob%'
    )

答案 1 :(得分:1)

您应该使用子查询fpor避免使用与其中的左联接表相关的列(这会产生内部联接)

SELECT `users`.`id`,
       `users`.`first_name` AS `firstName`,
       `users`.`last_name` AS `lastName`,
       `users`.`email`,
       t.`email` AS `usersSecondaryEmails.email`
FROM `Users` AS `users`
LEFT OUTER JOIN (       
    select `usersSecondaryEmails`.`user_id`,  `usersSecondaryEmails`.`email`
    from `UsersSecondaryEmails`
    where `usersSecondaryEmails`.`email` LIKE '%bob%') t on t.`user_id` = `users`.`id 
where (

    `users`.`first_name` LIKE '%bob%'
    OR `users`.`last_name` LIKE '%bob%'
    OR `users`.`email` LIKE '%bob%'
    )

答案 2 :(得分:1)

我相信你想要

SELECT u.`id`, u.`first_name` AS `firstName`, u.`last_name` AS `lastName`, u.`email`,
       us.`id` AS `usersSecondaryEmails.id`,
       us.`email` AS `usersSecondaryEmails.email`
FROM `Users` u LEFT OUTER JOIN
     `UsersSecondaryEmails` us
     ON u.`id` = us.`user_id`
WHERE (u.`first_name` LIKE '%bob%' OR u.`last_name` LIKE '%bob%' OR u.`email` LIKE '%bob%') OR
      EXISTS (SELECT 1
              FROM `UsersSecondaryEmails` us2
              WHERE us2.user_id = us.user_id AND us2.`email` LIKE '%bob%'
             );

这假设即使只有users中的字段都匹配,您仍需要所有第二封电子邮件。如果没有,则可以考虑。