2011-09-28 85 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

相關問題