如何找到顾客只有男人的商店?

时间:2019-01-31 11:23:30

标签: mysql sql

我有这个模式:

PERSON(姓名,性别)

FREQUENTS(名称,商店)

我的问题是,我如何找到客户专门为男性的商店?

4 个答案:

答案 0 :(得分:1)

您可以将GROUP BYHAVING一起使用:

SELECT frequents.shop
FROM frequents LEFT JOIN person ON frequents.name = person.name 
GROUP BY frequents.shop
HAVING SUM(person.sex = 'female') = 0 AND SUM(person.sex = 'male') > 0
  

demo at dbfiddle.uk

答案 1 :(得分:0)

select shop
from
(select shop , (case when sex = 'Male' then 1 else 2 end)s_cnt
from frequents a11 
join person a12
on a11.name = a12.name
group by shop , (case when sex = 'Male' then 1 else 2 end)
) a11
group by shop
having sum(s_cnt) = 1

答案 2 :(得分:0)

例如NOT EXISTS

select distinct shop
from frequents
where not exists (
    select 1
    from person
    where person.name = frequents.name and person.sex = 'female'
)

但是,根据this测试,最好使用IS NULL方法:

select distinct shop
from frequents
left join person on person.name = frequents.name and person.sex = 'female'
where person.name is null

答案 3 :(得分:0)

如果你只想要男人,那我想:

SELECT f.shop
FROM frequents f JOIN
     person p
     ON f.name = p.name 
GROUP BY f.shop
HAVING MIN(p.sex) = MAX(p.sex) AND  -- all sex values are the same or NULL
       COUNT(p.sex) = COUNT(*) AND  -- no NULL values
       MIN(p.sex) = 'male'          -- the value is male

此版本不假定只有两种性别。