【问题标题】:Create table with values from one column and another column without intersection使用来自一列和另一列的值创建表而没有交集
【发布时间】:2020-06-02 13:34:56
【问题描述】:

我有一张这样的桌子:

userid | clothesid
-------|-----------
  1    |   1
  1    |   3
  2    |   1
  2    |   4
  2    |   5

我想要这张表是这样的:

userid | clothesid
-------|-----------
  1    |   4
  1    |   5
  2    |   3

我该怎么做?

我已经用一个条目尝试过:

select distinct r.clothesid from table r where r.clothes not in (select r1.clothes from table r1 where r1.userid=1);

这会返回 4,5,但我不知道从哪里开始

【问题讨论】:

    标签: sql postgresql join select


    【解决方案1】:

    您可以cross joinuserids 的列表和clothesid 的列表生成所有组合,然后在原表上使用not exists 来识别缺失的行:

    select u.userid, c.clothesid
    from (select distinct userid from mytable) u
    cross join (select distinct clothesid from mytable) c
    where not exists(
        select 1 from mytable t on t.userid = u.userid and t.clothesid = c.clothesid
    )
    

    【讨论】:

      【解决方案2】:

      我想你想要:

      select (case when t1.clothesid is not null then 2 else 1 end),
             coalesce(t1.clothesid, t2.clothesid)
      from (select t.*
            from t
            where t.userid = 1
           ) t1 full join
           (select t.*
            from t
            where t.userid = 2
           ) t2
           on t1.clothesid = t2.clothesid
      where t1.clothesid is null or t2.clothesid is null;
      

      其实我觉得我有一个更简单的解决方案:

      select (case when min(t.userid) = 1 then 2 else 1 end), clothesid
      from t
      group by clothesid
      having count(*) = 1;
      

      Here 是一个 dbfiddle。

      【讨论】:

        【解决方案3】:

        useridclothesid的所有组合左连接到表中,只返回不匹配的行:

        select t1.userid, t2.clothesid
        from (select distinct userid from tablename) t1
        cross join (select distinct clothesid from tablename) t2
        left join tablename t on t.userid = t1.userid and t.clothesid = t2.clothesid
        where t.userid is null
        

        或与运营商EXCEPT

        select t1.userid, t2.clothesid
        from (select distinct userid from tablename) t1
        cross join (select distinct clothesid from tablename) t2
        except
        select userid, clothesid
        from tablename
        

        请参阅demo
        结果:

        > userid | clothesid
        > -----: | --------:
        >      1 |         4
        >      1 |         5
        >      2 |         3
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-28
          • 2022-01-24
          • 2021-08-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多