MySQLi一个ID有更多的记录

时间:2015-10-01 07:53:13

标签: php mysql

您好我有一个表格,其中存储了时间戳,一个项目的时间戳具有所有相同的ID,现在我希望每个项目只有最小的时间戳。

这就是我所拥有的:

$timeArr = array(23700, 23699, 23704, 23864);
foreach ($timeArr as $hido) {
    $mysqli = mysqli_connect("localhost", "root", "password", "dbname");
    if (!$mysqli) {
        die("Connection failed: " . mysqli_connect_error());
    }
    $sql = "SELECT clock FROM trends WHERE itemid = '$hido'";
    $re = mysqli_query($mysqli, $sql);
    while ($row = mysqli_fetch_assoc($re)) {

        $time = $row['clock'];


}

mysqli_free_result($re);
mysqli_close($mysqli);


}

我希望每个itemid只有最小/最旧的记录,我该怎么做?

编辑:时间戳的顺序应与数组中的Id相同。

3 个答案:

答案 0 :(得分:0)

你可以尝试

SELECT MIN(clock) FROM trends group by itemid

答案 1 :(得分:0)

试试这个:

$sql = "SELECT clock FROM trends WHERE itemid = '$hido' ORDER BY clock ASC LIMIT 1";

答案 2 :(得分:-1)

您需要捕获多个结果,因此我更改了代码以将MIN clock保存到由$hido值索引的数组中。

此外,您应该只connnect一次数据库,然后执行任意数量的查询,而不是每次要运行查询时都连接,所以我重新排序了一些代码

$mysqli = mysqli_connect("localhost", "root", "password", "dbname");
if (!$mysqli) {
    die("Connection failed: " . mysqli_connect_error());
}

$timeArr = array(23700, 23699, 23704, 23864);
$times = array();  // hold the min time for each itemid

foreach ($timeArr as $hido) {
    $sql = "SELECT MIN(clock) FROM trends WHERE itemid = '$hido'";

    $re = mysqli_query($mysqli, $sql);
    if ( ! $re ) {
        echo 'Connection failed: ' . mysqli_error();
        exit;
    }

    // as using MIN will mean you only get one row in your result set
    // you no longer need a while loop to process multiple result rows.
    $row = mysqli_fetch_assoc($re);

    $times[$hido] = $row['clock'];

    mysqli_free_result($re);
}


mysqli_close($mysqli);