如何从一个查询中排序两个表中的不同值?
问题描述:
- 表1:
country
,theOrderColumn1
- 表2:
country
,theOrderColumn2
我想加入这两个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
答
select distinct country
from (
select country, theOrderColumn from table1
union all
select country, theOrderColumn from table2
) a
order by theOrderColumn
答
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
答
select a.country,a.theOrderColumn
(
select country,theOrderColumn
from table1
union
select country,theOrderColumn
from table2
) a
order by a.theOrderColumn
虽然如果OrderColumn在表1和表2中不同,您将得到重复。
答
这取决于您想要什么以及如何将两个表连接在一起。如果您是基于“theOrderColumn”的加盟,那么查询将
SELECT DISTINCT country
FROM table1
JOIN table2 ON table1.theOrderColumn = table2.theOrderColumn
ORDER BY theOrderColumn
如果要在全国的加盟(这是没有意义的国家将是两个表中相同),那么你可以换加入条款中的“国家”。
此外,根据您DBMS所说的SQL方言,您的里程可能会因上述查询而异。你能澄清你更多吗?
答
如果要同时保留theOrderColumn1
和theOrderColumn2
给出的订单,可以使用列索引指定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
我编辑的问题,并解释更多... – ali