简体   繁体   English

如何从两列的值中选择 DISTINCT

[英]How to SELECT DISTINCT from values of two columns

I'd like to get the distinct values that occur in either of two columns (or in both).我想获得出现在两列(或两列)中的任何一列中的不同值。 Not the grouping of the columns, but the individual values themselves.不是列的分组,而是各个值本身。

For example, querying a table of air travel routes with columns ORIGIN and DESTINATION.例如,查询包含 ORIGIN 和 DESTINATION 列的航空旅行路线表。 I'd like to get the list of all airports, regardless of whether it is an origin or destination.我想获取所有机场的列表,无论是始发地还是目的地。

SFO, LGA
SFO, LAX
JFK, LAX
JFK, SFO
LAX, SFO
LAX, LGA

Should return应该返回

LAX, SFO, LGA, JFK

I am using Postgres 9.6 if it makes any difference.如果有任何区别,我正在使用 Postgres 9.6。

Just use union :只需使用union

select origin as airport
from routes
union  -- used on purpose to remove duplicates
select destination
from routes;

While writing my question, I managed to solve it, but I'm not sure if this is the most optimal case.在写我的问题时,我设法解决了它,但我不确定这是否是最佳情况。

SELECT DISTINCT orig AS airport_code
FROM (
  SELECT origin FROM airport_routes
  UNION ALL
  SELECT destination FROM airport_routes
);

研究在两列上使用聚合函数 (<,>)

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

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