Select 1 record from first table if condition is true in second table (all refeance rows active = 0)

时光毁灭记忆、已成空白 提交于 2019-12-11 11:27:27

问题


I have two tables. I want to select 1 record from first table if condition is true in second table (active = 0)

table Lead:

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

table LeadsDetails:

    -------------------------
    | id | lead_id | active |
    -------------------------
    | 1  | 1       | 1       |
    | 2  | 1       | 0       |
    | 3  | 2       | 0       |
    | 4  | 3       | 1       |
    | 5  | 4       | 0       |
    | 6  | 5       | 0       |
    | 7  | 5       | 0       |
    --------------------------

expected output:

    --------------
    | id | name   |
    --------------
    | 2  | abc2   |
    | 4  | abc4   |
    | 5  | abc5   |
    --------------

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

回答1:


This should run faster than not exists because the subquery won't run for every row; in this case I'm counting the number of situations where the active field value on table leadsdetails is not 0, for the given ID, and showing only rows where that count is 0 (ie. for the given id the active field is ALWAYS 0)

select l.id, l.name
  from lead l
  join leadsdetails ld
    on l.id = ld.lead_id
 group by l.id, l.name
having sum(case when ld.active <> 0 then 1 else 0 end) = 0

Fiddle: http://www.sqlfiddle.com/#!2/00970/2/0




回答2:


As you need to get the records only when active column doesn't have 1 use NOT EXISTS

SQL FIDDLE DEMO : http://www.sqlfiddle.com/#!2/00970/1

SELECT * FROM
Lead L
WHERE NOT EXISTS (
  SELECT 1 FROM LeasdDetails LD
  where L.id = LD.lead_id
  AND LD.active =1
)



回答3:


I think you can do what you want with an exists clause:

select l.*
from Lead l
where exists (select 1 from LeadsDetails ld where ld.lead_id = l.id and ld.active = 0)


来源:https://stackoverflow.com/questions/26204792/select-1-record-from-first-table-if-condition-is-true-in-second-table-all-refea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!