Sql 如何在一个查询中使用sort从两个表中选择不同的值?

Sql 如何在一个查询中使用sort从两个表中选择不同的值?,sql,distinct,Sql,Distinct,我有 表1:country,theOrderColumn1 表2:国家,第二列 我想加入这两个SELECT语句中不同的country: SELECT DISTINCT `country` FROM `table1` ORDER BY `theOrderColumn1` 及 例如: 表1(国家,理论列1):(英国,1),(美国,2) 表2(国家,理论专栏2):(法国,1),(英国,2) 我想要这个结果: france uk usa 尽管如果表1和表2中的theOrderColumn不同,您

我有

  • 表1:
    country
    theOrderColumn1
  • 表2:
    国家
    第二列
我想加入这两个SELECT语句中不同的
country

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

例如:

表1(国家,理论列1):(英国,1),(美国,2)

表2(国家,理论专栏2):(法国,1),(英国,2)

我想要这个结果:

france
uk
usa

尽管如果表1和表2中的theOrderColumn不同,您将得到重复的结果。

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

SELECT DISTINCT country 
FROM table1 
JOIN table2 ON table1.theOrderColumn = table2.theOrderColumn 
ORDER BY theOrderColumn
如果您想跨国家加入(这没有意义,因为两个表中的国家都是相同的),那么您可以在join子句中替换掉“country”


此外,根据DBMS使用的SQL方言,您的里程数可能会因上述查询而有所不同。您能进一步说明您的目的吗?

如果您想同时保留
theOrderColumn1
theOrderColumn2
给出的顺序,您可以使用列索引指定
orderby

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)

看看这个问题的答案:

如果您发布代码、XML或数据样本,请在文本编辑器中突出显示这些行,然后单击编辑器工具栏上的“代码样本”按钮(
{}
),以很好地格式化和语法突出显示它!
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
SELECT DISTINCT country 
FROM table1 
JOIN table2 ON table1.theOrderColumn = table2.theOrderColumn 
ORDER BY theOrderColumn
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)