0

ユニオン演算子を使用した内部選択クエリで order by 句を使用したい

select colname from table where <cond1> order by colname 
union
select colname from table where <cond2> order by colname 

完全な結果で order by を使用できますが、最初のクエリの結果を次の順序で並べ替え、次に 2 番目のクエリの結果を次の順序で並べたいと考えています。

その上でいくつかの提案をお願いします。

4

3 に答える 3

1

intableの正しい使用法Order byunioned

select colname from table where <cond1> 
union
select colname from table where <cond2> order by colname

上記のコードの説明は、2つのクエリが結合された後、列名に基づいて並べ替えるというものです。サーバーが最初のクエリと結合する前に、最初に下位のクエリを並べ替えることはありません。しかし、それに代わる方法があります。サブクエリでラップする必要があります。

SELECT newTable.colname
FROM
(
    select colname, 1 as OrderThis from table where <cond1> 
    union
    select colname, 2 as OrderThis from table where <cond2> 
) newTable
Order by newTable.OrderThis, newTable.colname

私があなたの考えを正しく理解した場合union、2つのクエリを正しくして正しい位置を維持する前に、最初に列を並べ替えます(最初のクエリ結果は上に残り、2番目のクエリ結果は最初のクエリの下に残ります

于 2012-07-28T07:28:08.643 に答える
0

これはトリックを行う可能性があります

SELECT * FROM ( SELECT colname  FROM table1 where <cond1> order by colname ) DUMMY_ALIAS1

UNION ALL

SELECT * FROM ( SELECT colname  FROM table2 where <cond2> order by colname ) DUMMY_ALIAS2
于 2012-07-28T07:27:47.600 に答える
0

次のことを行う必要があります...私は推測します

select colname,1 as OrderCol from table where <cond1> 
union select colname,2 as OrderCol  from table 
where <cond2>  
order by OrderCol
于 2012-07-28T07:25:37.033 に答える