为什么我的值在数据库中按升序保存?

Why are my values being saved in ascending order in the database?

我刚刚注意到我的 rand 值是按升序(从低到高)保存的,但我并没有告诉它按升序保存。然而,当我回应兰特时,它以正常方式显示价值。

源代码:

<?php
try {
  $db = new PDO('sqlite:randvalue.sqlite');
  $db->exec("CREATE TABLE company (revenue_value INTEGER PRIMARY KEY, month VARCHAR)");

  $i=1;
  while($i <= 12) {
    $randNum =  rand(1,100);
    $finalval = $randNum;
    $stmt = $db->prepare('INSERT INTO company (revenue_value) VALUES (?)');
    $stmt->execute(array("$finalval"));
    echo "$finalval";
    echo "<br>";
    $i++;
  };

  print "<table border=1>";
  print "<tr><td>value</td>";
  $result = $db->query('SELECT * FROM company');

  foreach($result as $row) {
    print "<tr><td>".$row['revenue_value']."</td>";
  }
  print "</table>";

  $db = NULL;

} catch(PDOException $e) {
  print 'Exception : '.$e->getMessage();
}
?>

结果:

如何使 table 中的值不按非升序保存,就像在 echo 中值不是按升序排列一样?

感谢@Rizier 设法找到了问题

只删除主键

$db->exec("CREATE TABLE company (revenue_value INTEGER PRIMARY KEY, month VARCHAR)");

  $db->exec("CREATE TABLE company (revenue_value INTEGER, month VARCHAR)");

数据库将尝试以最有效的方式存储行以进行快速查找。这意味着按照 table 的 primary key 定义的顺序存储它们,如果存在的话,在这种情况下,revenue_value 列是主键。无法保证插入记录的顺序就是执行 SELECT 时它们返回的顺序。

如果您想以相同的顺序返回记录,则需要一个单独的列来存储它们的插入顺序。通常,您会使用 AUTO_INCREMENT column that's also the primary key of the table. Add a column like this and you'll be able to pull them back in the order in which they are inserted by using an ORDER BY 子句。然而,正如我所说,数据库通常会尝试有效地存储行,无论如何它都会按主键列对它们进行排序,所以通常你不会需要 ORDER BY , 但在结果顺序很重要的任何查询中包含一个仍然是个好主意。