H2在具有限制行为的多个列上排序

时间:2013-03-21 14:40:42

标签: sql limit h2 sql-order-by

使用多个排序列时输出是否正常并且这些列的顺序是否变化是正常的吗?

例如:

create table test_table (
    id int8 not null,
    year int4 not null,
    province varchar(16) not null,
    dangerous bool,
    sector varchar(9) not null,
    unit varchar(3) not null,
    amount numeric not null
);



insert into test_table (id, year, province, dangerous, sector, unit, amount) values (1, 2012, 'W_FL', true, 'FOTOG', 'TNE', 55);
insert into test_table (id, year, province, dangerous, sector, unit, amount) values (2, 2012, 'E_FL', true, 'CHEM', 'TNE', 54);
insert into test_table (id, year, province, dangerous, sector, unit, amount) values (3, 2012, 'W_FL', true, 'CHEM', 'TNE', 74);
insert into test_table (id, year, province, dangerous, sector, unit, amount) values (4, 2012, 'E_FL', true, 'FOTOG', 'TNE', 4);
insert into test_table (id, year, province, dangerous, sector, unit, amount) values (5, 2012, 'LIM', true, 'FOTOG', 'TNE', 4);

首先查询:

select
    * 
from
    test_table test 
where
    test.year=2012
order by
    test.province asc,
    test.sector asc 
limit 2;

哪个输出:

ID      YEAR    PROVINCE    DANGEROUS   SECTOR      UNIT    AMOUNT  
2       2012    E_FL        TRUE        CHEM        TNE     54
4       2012    E_FL        TRUE        FOTOG       TNE     4

第二个查询:

select
    * 
from
    test_table test 
where
    test.year=2012
order by
test.sector asc,
    test.province asc
limit 2;

此查询返回其他内容:

ID      YEAR    PROVINCE    DANGEROUS   SECTOR      UNIT    AMOUNT 
2       2012    E_FL        TRUE        CHEM        TNE     54
3       2012    W_FL        TRUE        CHEM        TNE     74

好像只有二级by by子句被限制使用了...... 有人可以验证我的假设,即两个查询都应该产生相同的输出吗?

1 个答案:

答案 0 :(得分:1)

如果从查询中删除LIMIT 2,您将看到订单:

首次查询

 ---- ------ ---------- ----------- -------- ------ -------- 
| id | year | province | dangerous | sector | unit | amount |
 ---- ------ ---------- ----------- -------- ------ -------- 
|  2 | 2012 | E_FL     |         1 | CHEM   | TNE  |     54 |
|  4 | 2012 | E_FL     |         1 | FOTOG  | TNE  |      4 |
|  5 | 2012 | LIM      |         1 | FOTOG  | TNE  |      4 |
|  3 | 2012 | W_FL     |         1 | CHEM   | TNE  |     74 |
|  1 | 2012 | W_FL     |         1 | FOTOG  | TNE  |     55 |
 ---- ------ ---------- ----------- -------- ------ -------- 

第二次查询

 ---- ------ ---------- ----------- -------- ------ -------- 
| id | year | province | dangerous | sector | unit | amount |
 ---- ------ ---------- ----------- -------- ------ -------- 
|  2 | 2012 | E_FL     |         1 | CHEM   | TNE  |     54 |
|  3 | 2012 | W_FL     |         1 | CHEM   | TNE  |     74 |
|  4 | 2012 | E_FL     |         1 | FOTOG  | TNE  |      4 |
|  5 | 2012 | LIM      |         1 | FOTOG  | TNE  |      4 |
|  1 | 2012 | W_FL     |         1 | FOTOG  | TNE  |     55 |
 ---- ------ ---------- ----------- -------- ------ -------- 

第二个订单将永远不会改变第一个订单的顺序。它将仅应用于第一个order by具有重复条目的行组。

因此,您将从这两个查询中获得这些截然不同的结果。