Order object / Sql order by string 无法与对象一起正常工作

Order object / Sql order by string not working properly with object

我试图直接在 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 为什么

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

Space在a之前,所以排序是正确的。

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

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

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