如果所有引导活动= 0且第二个表中的primary_email =是,则MySQL INNER JOIN仅从第一个表中选择一行

时间:2014-10-05 06:53:41

标签: mysql sql join inner-join

我有两张桌子。 我想以一种方式加入它们,如果leads_details表所有lead_id active = 0和primary = Yes,则只有一个记录在潜在客户表中。

表主管:

    -------------
    | id | name |
    -------------
    | 1  | abc1 |
    | 2  | abc2 |
    | 3  | abc3 |
    | 4  | abc4 |
    | 5  | abc5 |
    -------------

表LeadsDetails:

    --------------------------------------
    | id | lead_id | active | primary_email
    --------------------------------------
    | 1  | 1       | 1       |Yes         |
    | 2  | 1       | 0       |NO          |
    | 3  | 2       | 0       |Yes         |
    | 4  | 3       | 1       |Yes         |
    | 5  | 4       | 0       |Yes         |
    | 6  | 5       | 1       |NO          |
    -------------------------------------

预期产出:

    --------------
    | id | name   |
    --------------
    | 1  | abc2   |
    | 2  | abc4   |
    --------------

SELECT `Lead`.`id`, `Lead`.`name`, `Lead`.`unsubscribe` 
FROM `leads` AS `Lead` inner JOIN `LeadsDetails` AS `LeadsDetails` 
ON (`LeadsDetails`.`lead_id` = `Lead`.`id`) 
WHERE `LeadsDetails`.`primary_email` = 'Yes' AND `LeadsDetails`.`active` = 0

1 个答案:

答案 0 :(得分:2)

您需要按属性分组

 SELECT `Lead`.`id`, `Lead`.`name`, `Lead`.`unsubscribe` 
FROM `leads` AS `Lead` inner JOIN `LeadsDetails` AS `LeadsDetails` 
ON (`LeadsDetails`.`lead_id` = `Lead`.`id`) 
WHERE `LeadsDetails`.`primary_email` = 'Yes' AND `LeadsDetails`.`active` = 0
GROUP BY lead.id