【问题标题】:Order object / Sql order by string not working properly with objectOrder object / Sql order by string 无法与对象一起正常工作
【发布时间】:2021-08-26 19:39:35
【问题描述】:

我正在尝试直接在 SQL 查询中或使用 Js 函数对对象数组进行排序,但结果未排序,或者其中一半已排序。

这是我的 SQL 调用:

controller.getCandidatos = (req, res) => {
  req.getConnection((err, conn) => {
    conn.query('SELECT c.id, c.nombre, c.apellido, c.empresa, c.imagen, c.id_entidad, e.nombre as enti FROM candidato c left join entidad e on c.id_entidad = e.id ORDER BY c.nombre ASC', (err, rows) => {
      if (err) {
        console.log(err);
      }
      res.send(rows);
    });
  });

我明白了:

[
  { "id": 113, "nombre":" Antinori", "apellido": null, "empresa": "Cecilia Guzmán Arriagada", "imagen": null, "id_entidad": null, "enti": null },
  { "id": 67, "nombre": " Aresti", "apellido": null, "empresa": "Matías Rivera", "imagen": null, "id_entidad": null, "enti": null },
  { "id": 84, "nombre": " Balduzzi", "apellido": null, "empresa": "Gustavo  Balduzzi ", "imagen": null, "id_entidad": null, "enti": null },
....
{ "id": 108, "nombre": " Viu Manent", "apellido": null, "empresa": "José Miguel Viu", "imagen": null, "id_entidad": null, "enti": null },
  { "id": 13, "nombre": "Abraham Lincoln", "apellido": null, "empresa": "Estados Unidos", "imagen": "lincol.jpg", "id_entidad": null, "enti": null },

在最后一个对象之后,它再次从“A”开始排序,但数组分成了一半。

我正在尝试使用此功能,但得到了相同的结果。

function dynamicSort(property) {
        var sortOrder = 1;
        if(property[0] === "-") {
            sortOrder = -1;
            property = property.substr(1);
        }
        return function (a,b) {
            var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
            return result * sortOrder;
        }
    }

当我以任何一种方式按“apellido”等其他列排序时,数组排序开始变得奇怪,IDK 为什么

【问题讨论】:

    标签: javascript html node.js ejs


    【解决方案1】:

    您获得的前几个结果的nombre 列中的值以空格开头。

    a前面有空格,所以排序是正确的。

    您可以按修剪后的文本进行排序:

    ... ORDER BY TRIM(c.nombre) ASC
    

    (但这将阻止在c.nombre 上使用索引,如果有的话;至少在 MySQL 的情况下)。

    【讨论】:

    • 天啊,我花了这么长时间才看到你
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2021-07-11
    • 2014-06-18
    • 2023-02-06
    • 2021-12-18
    • 1970-01-01
    • 2019-03-21
    相关资源
    最近更新 更多