简体   繁体   English

使用来自一列和另一列的值创建表而没有交集

[英]Create table with values from one column and another column without intersection

I have a table like so:我有一张这样的桌子:

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

What I want from this table is a table like so:我想从这张桌子上得到一张像这样的桌子:

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

How can I do this?我怎样才能做到这一点?

I've tried it with one entry as:我已经尝试过一个条目:

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

and this returns 4,5, but I'm not sure where to proceed from here这返回 4,5,但我不知道从哪里开始

You can cross join the list of userid s and the list of clothesid to generate all combinations, and then use not exists on the original table to identify the missing rows:您可以将userid的列表和clothesid id 的列表cross join以生成所有组合,然后在原始表上使用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
)

I think you want:我想你想要:

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;

Actually, I think I have a simpler solution:实际上,我认为我有一个更简单的解决方案:

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

Here is a db<>fiddle. 是一个 db<>fiddle。

Left join all the combinations of userid and clothesid to the table and return only the unmatched rows:将所有useridclothesid ID 的组合左连接到表中,并仅返回不匹配的行:

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

Or with the operator EXCEPT :或使用运算符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

See the demo .请参阅演示
Results:结果:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM