如何在一个查询中从2个表中选择不同的值并进行排序?

时间:2011-09-28 13:38:27

标签: sql distinct

我有

  • table1:countrytheOrderColumn1
  • table2:countrytheOrderColumn2

我想从这两个SELECT语句中加入DISTINCT country

SELECT DISTINCT `country` FROM `table1` ORDER BY `theOrderColumn1`

SELECT DISTINCT `country` FROM `table2` ORDER BY `theOrderColumn2`

示例:

table1 (country, theOrderColumn1): (uk, 1), (usa, 2)
table2 (country, theOrderColumn2): (france, 1), (uk, 2)

我想要这个结果:

france
uk
usa

5 个答案:

答案 0 :(得分:22)

select distinct country
from (
    select country, theOrderColumn from table1
    union all
    select country, theOrderColumn from table2
) a 
order by theOrderColumn

答案 1 :(得分:2)

select country, theOrderColumn from (
select distinct t1.country as country, t1.theOrderColumn as theOrderColumn from table t1
union
select distinct t2.country as country, t2.theOrderColumn as theOrderColumn from table t2) t3
order by theOrderColumn

答案 2 :(得分:1)

select a.country,a.theOrderColumn
(
select country,theOrderColumn
from table1
union
select country,theOrderColumn
from table2
) a
order by a.theOrderColumn

如果表1和表2中的OrderColumn不同,您将获得重复。

答案 3 :(得分:1)

这取决于您的需求以及您希望如何将两个表连接在一起。如果您基于“theOrderColumn”加入,则查询将是

SELECT DISTINCT country 
FROM table1 
JOIN table2 ON table1.theOrderColumn = table2.theOrderColumn 
ORDER BY theOrderColumn

如果你想在全国范围内加入(由于两个表格中的国家相同而没有意义),那么你可以在连接条款中换掉“country”。

此外,根据您的DBMS所说的SQL方言,您的里程可能会因上述查询而异。你能澄清一下你所追求的更多内容吗?

答案 4 :(得分:1)

如果要同时保留theOrderColumn1theOrderColumn2给出的顺序,可以使用列索引指定ORDER BY列。

SELECT distinct country FROM(

  (SELECT country as c, theOrderColumn1 as d from table1
  UNION
  SELECT country as c, theOrderColumn2 as d from table2
  )
  order by 2
)

看看这个问题的答案:SQL Query - Using Order By in UNION

相关问题