sql—创建一个表,其中包含一列和另一列中的值,且不相交

az31mfrm  于 2021-08-09  发布在  Java
关注(0)|答案(3)|浏览(351)

我有一张这样的table:

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

我想要的是这样一张table:

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,但我不确定从这里开始

mnemlml8

mnemlml81#

你可以 cross join 名单 userid s和 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
)
cigdeys3

cigdeys32#

我想你想要:

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;

这是一把小提琴。

dddzy1tm

dddzy1tm3#

左键连接所有 userid 以及 clothesid 返回表并仅返回不匹配的行:

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

请看演示。
结果:

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

相关问题