Heim  >  Fragen und Antworten  >  Hauptteil

Warum speichert MySQL JSON in umgekehrter Reihenfolge? wie man es repariert

Dies ist der Code zum Einfügen von JSON in mein SQL

function insert_ema($json){

$a= new Sql();
$b=$a->connection;
$sql = "INSERT INTO ema (ema_ten) VALUES ('$json')";

if ($b->query($sql) === TRUE) {
echo PHP_EOL." New record created successfully \n";
} else {
echo PHP_EOL." Error: " . $sql . "<br>" . $b->error;
}
$b->close();


;}

insert_ema('{"firstName":"John", "lastName":"Doe","3":"Jo", "4":"Do"}');

+----------------------------------------------------------------+----+
| ema_ten                                                        | id |
+----------------------------------------------------------------+----+
| {"3": "Jo", "4": "Do", "lastName": "Doe", "firstName": "John"} |  1 |
| {"3": "Jo", "4": "Do", "lastName": "Doe", "firstName": "John"} |  2 |
+----------------------------------------------------------------+----+

Die oben gespeicherte SQL-Anweisung ist in umgekehrter Reihenfolge! ! Wie kann ich es beheben

Der Grund, warum ich mich an die Reihenfolge halten möchte, ist, dass ich den JSON in ein Array konvertieren und pop verwenden möchte.

Ich denke, MySQL sollte das Array für dieses Problem speichern und sortieren.

P粉141925181P粉141925181245 Tage vor342

Antworte allen(1)Ich werde antworten

  • P粉090087228

    P粉0900872282024-02-18 11:01:52

    https://dev.mysql.com/doc/refman /8.0/en/json.html 说:

    这意味着您不应依赖 JSON 对象中键的任何特定排序顺序。 JSON 数组有顺序,但 JSON 对象的键没有。

    如果 JSON 对象的键和各自的值相同,则无论顺序如何,它们都是相等的:

    mysql> select cast('{"firstName":"John", "lastName":"Doe","3":"Jo", "4":"Do"}' as json) 
      = cast('{"3": "Jo", "4": "Do", "lastName": "Doe", "firstName": "John"}' as json) 
      as is_equal;
    +----------+
    | is_equal |
    +----------+
    |        1 |
    +----------+

    回复您的评论:

    上面例子的要点是你不能让MySQL按照你想要的顺序存储键。 MySQL 的 JSON 实现并没有做到这一点。它重新排列 JSON 对象键以提高查找效率。你对此没有发言权。

    JSON 数组可以排序。因此,保留顺序的唯一选择是使用数组,其中数组的每个元素都是具有单个键的对象:

    [{"firstName":"John"}, {"lastName":"Doe"}, {"3":"Jo"}, {"4":"Do"}]

    我知道这不是您所要求的,但您所要求的在 MySQL 中无法实现。

    Antwort
    0
  • StornierenAntwort