提问者:小点点

列表中有重复值的SQL查询


如何正确地编写查询以获取没有唯一性的数据?

我有一个ID列表,其中ID是重复的。

示例:(1,1,1,2,3)

select * 
from table 
where id in (1,1,1,2,3);

仅返回(1,2,3)。

但我需要处理重复的条目。


共2个答案

匿名用户

使用派生表和左联接:

select t.*
from (select 1 as id union all select 1 union all select 1 union all select 2 union all select 3
     ) i left join
     t
     on t.id = i.id

派生表的语法可能因数据库而异,但大多数都支持上述语法。

匿名用户

这不是WHERE语句的作用,因为它只用于筛选匹配的键。

如果需要按此顺序执行,请使用

select table.* 
from (
  select 1 as id
  union select 1
  union select 1
  union select 2
  union select 3
) myStaticKeys
join table using (id)