选择联合作为不同的
执行 UNION 后如何对单列执行 DISTINCT 操作?
T1
--
ID Value
1 1
2 2
3 3
T2
--
ID Value
1 2
4 4
5 5
我正在尝试返回表格:
ID Value
1 1
2 2
3 3
4 4
5 5
我尝试过:
SELECT DISTINCT ID, Value
FROM (SELECT*FROM T1 UNION SELECT*FROM T2) AS T3
这似乎不起作用。
How do I perform a DISTINCT operation on a single column after a UNION is performed?
T1
--
ID Value
1 1
2 2
3 3
T2
--
ID Value
1 2
4 4
5 5
I am trying to return the table:
ID Value
1 1
2 2
3 3
4 4
5 5
I tried:
SELECT DISTINCT ID, Value
FROM (SELECT*FROM T1 UNION SELECT*FROM T2) AS T3
This does not seem to work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为什么要使用子查询?这将起作用:
UNION
删除重复项。 (UNION ALL
没有)Why are you using a sub-query? This will work:
UNION
removes duplicates. (UNION ALL
does not)据我所知,不存在“单列
distinct
”:distinct
始终应用于整个记录(除非在像count(独特的名称)
)。原因是,SQL 无法猜测要为您保留哪些Value
值以及要删除哪些值。这是你需要自己定义的东西。尝试使用
GROUP BY
来确保ID
不重复,以及任何聚合(此处MIN
,如您的示例中所示,它是幸存的最小值)选择Value
的特定值:应该正是您所需要的。也就是说,它不是同一个查询,并且没有
不同
,但它是一个将返回示例中所示内容的查询。As far as I can say, there's no "one-column
distinct
":distinct
is always applied to a whole record (unless used within an aggregate likecount(distinct name)
). The reason for this is, SQL cannot guess which values ofValue
to leave for you—and which to drop. That's something you need to define by yourself.Try using
GROUP BY
to ensureID
is not repeated, and any aggregate (hereMIN
, as in your example it was the minimum that survived) to select a particular value ofValue
:Should be exactly what you need. That is, it's not the same query, and there's no
distinct
—but it's a query which would return what's shown in the example.我想这就是你的意思:
I think that's what you meant:
这 - 尽管这个线程很旧 - 可能是OP问题的有效解决方案,即使它可能被认为是脏的。
我们从第一个表中选择所有元组,
然后将其与第二个表中的元组添加(联合),仅限于第一个表中没有匹配的特定字段的元组。
This - even though this thread is way old - might be a working solution for the question of the OP, even though it might be considered dirty.
We select all tuples from the first table,
then adding (union) it with the tuples from the second table limited to those that doe not have the specific field matched in the first table.