2011-09-28 82 views
3

如何从一个查询中排序两个表中的不同值?

  • 表1:countrytheOrderColumn1
  • 表2: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 

回答

14
select distinct country 
from (
    select country, theOrderColumn from table1 
    union all 
    select country, theOrderColumn from table2 
) a 
order by theOrderColumn 
1
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 
1
select a.country,a.theOrderColumn 
(
select country,theOrderColumn 
from table1 
union 
select country,theOrderColumn 
from table2 
) a 
order by a.theOrderColumn 

虽然如果OrderColumn在表1和表2中不同,您将得到重复。

+0

我编辑的问题,并解释更多... – ali

1

这取决于您想要什么以及如何将两个表连接在一起。如果您是基于“theOrderColumn”的加盟,那么查询将

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

如果要在全国的加盟(这是没有意义的国家将是两个表中相同),那么你可以换加入条款中的“国家”。

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

+1

如果您发布的代码,XML或数据样本,** **请在突出那些行文本编辑器并单击编辑器工具栏上的“代码示例”按钮(“{}”),以良好地格式化和语法突出显示它! –

+0

我编辑问题并解释更多... – ali

+0

错误#1052 - 字段列表中的列'country'不明确。 – ali

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

相关问题