AlaSQL & Order BY 子句与日期

AlaSQL & ORDER BY clause with dates

提问人:Fabrice 提问时间:4/22/2022 最后编辑:Fabrice 更新时间:5/17/2022 访问量:361

问:

我需要按日期和事件对数据进行排序,但我正在努力使用 Date 对象上的 AlaSQL 查询让它工作:

function testOrderBy() {
  var data = [{event:'A', date: new Date('2021-04-21')},
    {event:'B', date: new Date('2021-04-21')},
    {event:'C', date: new Date('2021-04-21')},
    {event:'D', date: new Date('2021-04-20')}];

  console.log(data);
  var res = alasql(`SELECT event, date FROM ? ORDER BY date, event`, [data]);
  console.log(res);
}

得到的结果是:

[ { event: 'D',
    date: Tue Apr 20 2021 02:00:00 GMT+0200 (Central European Summer Time) },
  { event: 'C',
    date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
  { event: 'B',
    date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
  { event: 'A',
    date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) } ]

我期待:

[ { event: 'D',
    date: Tue Apr 20 2021 02:00:00 GMT+0200 (Central European Summer Time) },
  { event: 'A',
    date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
  { event: 'B',
    date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) },
  { event: 'C',
    date: Wed Apr 21 2021 02:00:00 GMT+0200 (Central European Summer Time) } ]

如果日期不是 Date 对象而是 ISO 字符串,则不会出现此问题:

function testOrderBy() {
  var data = [{event:'A', date: '2021-04-21'},
    {event:'B', date: '2021-04-21'},
    {event:'C', date: '2021-04-21'},
    {event:'D', date: '2021-04-20'}];

  console.log(data);
  var res = alasql(`SELECT event, date FROM ? ORDER BY date, event`, [data]);
  console.log(res);
}

结果符合预期D, A, B, C

有什么想法吗?

JavaScript AlaSQL

评论

0赞 Salman A 4/22/2022
“SQL标准”说,如果两个值在顺序上相等,那么它们的相对顺序取决于实现。 并且都是正确的。D, A, B, CD, B, C, A
0赞 Fabrice 4/22/2022
好的,但它看起来像一个 AlaSQL 问题。排序是 D、A、B、C 使用字符串格式的日期,但 D、B、C、A 使用 Date 对象
0赞 Salman A 4/22/2022
两个顺序都是正确的。关键是没有根据SQL标准进行保证。

答:

0赞 Fabric.io 5/17/2022 #1

必须创建表架构才能正确地将列视为 Date 类型,如下所示:

alasql("CREATE TABLE events (event string, date date)");
alasql.tables.events.data = [{event:'A', date: new Date('2021-04-21')},
    {event:'B', date: new Date('2021-04-21')},
    {event:'C', date: new Date('2021-04-21')},
    {event:'D', date: new Date('2021-04-20')}];

alasql(`SELECT event, date INTO HTML("#res") FROM events ORDER BY date, event`);
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/alasql.min.js"></script>
<div id="res">

</div>