【问题标题】:How to select distinct values from 2 tables with sort in one query?如何在一个查询中通过排序从 2 个表中选择不同的值?
【发布时间】:2011-11-26 21:39:02
【问题描述】:

我有

  • 表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

【问题讨论】:

    标签: sql distinct


    【解决方案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

    【讨论】:

      【解决方案2】:
      select distinct country
      from (
          select country, theOrderColumn from table1
          union all
          select country, theOrderColumn from table2
      ) a 
      order by theOrderColumn
      

      【讨论】:

        【解决方案3】:

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

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

        如果您想跨国家/地区加入(这没有意义,因为两个表中的国家/地区相同),那么您可以在 join 子句中换掉“国家”。

        此外,根据您的 DBMS 使用的 SQL 方言,您的里程可能会因上述查询而异。你能澄清更多你在追求什么吗?

        【讨论】:

        • 如果您发布代码、XML 或数据示例,在文本编辑器中突出显示这些行,然后单击编辑器上的“代码示例”按钮 ({ })工具栏以很好地格式化和语法突出显示它!
        【解决方案4】:
        select a.country,a.theOrderColumn
        (
        select country,theOrderColumn
        from table1
        union
        select country,theOrderColumn
        from table2
        ) a
        order by a.theOrderColumn
        

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

        【讨论】:

          【解决方案5】:
          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
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2012-10-15
            • 1970-01-01
            • 2013-10-14
            • 1970-01-01
            • 2022-01-18
            • 1970-01-01
            • 2018-06-20
            相关资源
            最近更新 更多