JSON 响应未根据 SQL 查询正确排序

JSON response is not ordering properly according to SQL query

本文关键字:查询 排序 SQL 响应 JSON      更新时间:2023-09-26

我的JSON数组有问题。在第一次加载时,顺序不是应有的(如 SQL 查询中所定义)。

所以主要问题是,在页面加载时,即当使用 lastPoll=null 调用 SQL 查询时 - 结果不是按 time1 DESC 排序的,而是按 s.id ASC 排序的。当我输入一个新结果,然后在查询中设置了lastPoll运行查询时,最新的结果将添加到顶部,因为它应该是。

奇怪的部分是 - 如果我在 URL 中使用正确的参数查看推送时的原始 JSON 响应.php则响应是正确的并且顺序正确。那么,问题一定出在解析上吗?

下面是 SQL 查询:

$getActivityUpdates1 = mysql_query("
    SELECT
        s.id, u.name, u.profilePic, s.userid,  s.content, s.time1, s.imageKey
    FROM
        status_updates s 
    INNER JOIN
        users1 u ON u.id = s.userid 
    WHERE
        competitionId = '$competitionId' AND s.time1 > '$lastPoll'
    ORDER BY s.time1 DESC");
$results = array('items' => array());
while ($row = mysql_fetch_array($getActivityUpdates1)) 
{
    $results['items'][] = array(
    'statusid' => $row['id'],
    'name' => $row['name'], 
    'profilePic' => $row['profilePic'],
    'content' => $row['content'],
    'time1' => $row['time1'],
    'imageKey' => $row['imageKey'],
    );
}
die(json_encode($results));
?>

这是我重新运行查询的 Javascript。

var lastPoll = null;     
function loadActivity(onDone) {
    var competitionId = $("body").attr("data-competitionId");
    console.log(lastPoll);
    if (lastPoll == null) { // We have never polled, we want to pull everything and populate  the list.
        url = "push.php?competitionId=" + competitionId + "&lastPoll=1999-01-01 22:00:00"; 
    } else { // We have polled once, send the date and time of that last poll to capture only new entries.
        url = "push.php?competitionId=" + competitionId + "&lastPoll=" + lastPoll;   
    }
    $.get(url, function(data) {
        jsonData = $.parseJSON(data);
        var spot = $("#activityspot");
        var template = spot.find(".template");
        for (var j = 0; j < jsonData.items.length; j++) {
            var entryData = jsonData.items[j];
            var entry = template.clone();
            entry.removeClass("template");
            entry.find(".message").text(entryData.statusid);
            spot.prepend(entry);
        }
        if (onDone) {
            onDone();
        }
        lastPoll = js_yyyy_mm_dd_hh_mm_ss();
    });
}

您以相反的时间顺序生成结果,但也以相反的顺序将它们添加到页面(带有 .prepend )。 最终结果是两个反转相互抵消,以便每批结果按时间升序添加到列表顶部。

如果目的是实际以相反的顺序显示它们,只需从查询中删除DESC限定符,并依靠.prepend调用将每个连续条目添加到页面顶部。