【问题标题】:How to join tables without loosing rows that aren't in both of them?如何在不丢失两个表中都不存在的行的情况下连接表?
【发布时间】:2015-01-06 07:53:58
【问题描述】:

我有两张桌子:Artist 和 Artwork。下面是关于艺术家姓名的 INNER JOIN = artist.artist

我需要列出男性作品多于女性作品的城市。

首先我知道每个城市有多少男性创作的艺术品:

select location, count(gender) from 
(artist inner join artwork on name = artist) 
where gender="male" group by location;

得到

然后我也会这样做,只是针对女性艺术家。

select location, count(gender) from 
(artist inner join artwork on name = artist) 
where gender="female" group by location;

我从这里去哪里? 我尝试 LEFT JOINing 获得的表并从中选择城市 WHERE 男性 > 女性。

像这样:

select city_male from ( 

    (select location as city_male, count(gender) as male_art from (artist inner join artwork on name = artist)
    where gender="male" group by location)

    LEFT JOIN

    (select location as city_female, count(gender) as female_art from (artist inner join artwork on name = artist)
    where gender="female" group by location)

    on city_female = city_male

)
where male_art > female_art
;

我得到的结果接近我需要的结果,但是只有一种性别的艺术品的城市在加入后会丢失。

如何将这些表格合二为一,选出男性作品多于女性作品的城市?

【问题讨论】:

    标签: sql join


    【解决方案1】:

    where 子句移至on 子句:

    on city_female = city_male and male_art > female_art
    

    如果没有匹配,你仍然会得到城市。

    我认为使用group byhaving 编写查询会更容易:

    select location as city_male,
           sum(case when gender = 'male' then 1 else 0 end) as male_art,
           sum(case when gender = 'female' then 1 else 0 end) as female_art
    from artist inner join
         artwork
         on name = artist)
    group by location
    having sum(case when gender = 'male' then 1 else 0 end) > sum(case when gender = 'female' then 1 else 0 end);
    

    【讨论】:

      猜你喜欢
      • 2017-04-30
      • 1970-01-01
      • 2021-09-12
      • 1970-01-01
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多