dongtong2021 2011-07-25 18:57 采纳率: 0%
浏览 41

从数据库中排序检索到的信息

I'm creating a feed by retrieving information from my database using nested while loops (is there a better way to do this?).

I have one table called users with all the names amongst other things. The other table is called messages which has messages, the user who posted it, and a timestamp.

$userQuery = mysql_query("SELECT name FROM users");
while ($user = mysql_fetch_array($userQuery, MYSQL_NUM)) {
    $messageQuery = mysql_query("SELECT message FROM messages WHERE user = $user ORDER BY timestamp DESC");
    while ($message = mysql_fetch_array($messageQuery, MYSQL_NUM)) {
        echo "$user[0]: $message[0]";
    }
}

The problem is that it doesn't order by the timestamp and I can't tell how it's ordered. I've tried timestamp, datetime, and int types with UNIX timestamps.

EDIT: I should add that the user and message matches up fine, it's just the ordering that doesn't work.

  • 写回答

2条回答 默认 最新

  • douya5194 2011-07-25 19:03
    关注

    I guess you get your users in more or less random order and "within" one user the sorting is ok?!

    use:

    $result = mysql_query('select users.name,messages.message from messages join users on (users.name=messages.user) order by messages.timestamp');
    while($row = mysql_fetch_row($result))
        echo "$row[0]: $row[1]";
    

    That should give you an ordered result (at least if you have a column called messages.timestamp. Check the name ;-)). And all in one query...

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?