duandazhen7306 2016-02-03 13:51
浏览 79
已采纳

如何在顶级和离线后显示在线用户呢?

Could you guys please tell me how to show all online people on the top and all offline after, both lists in ascending order of the username just like Skype does.

My MySQL table is Users, and the columns are as follow:

ID
Username
Last_logged_in - is with unix_timestamp();

the code I am using to show online people is as follow:

select * from users where Last_logged_in >= UNIX_TIMESTAMP() - 60;

and the code I tried was like so:

select id, username,  last_logged_in from users where last_logged_in >= UNIX_TIMESTAMP() - 60 UNION select id, username,  last_logged_in from users where  last_logged_in <= UNIX_TIMESTAMP() - 60 LIMIT 10;

some helps will be really appreciated.

  • 写回答

2条回答 默认 最新

  • dougong7850 2016-02-03 14:03
    关注

    Your query doesn't provide the results you expect because UNION does not preserve the order of the rows from the queries it unions.

    You need to enclose each of the unioned queries into parentheses and add ORDER BY after the last query. However, if you do that you obtain a big and slow query that selects all the records from table users in a convoluted way.

    The solution is to order the rows descending by column Last_logged_in. This way, the users that logged in recently are returned first. Also you need to add in the fields list the expression that tells if the user is still online. Finally, because your query does not filter the returned users, a LIMIT clause is recommended; otherwise the query will return the entire table which is probably not what you want.

    Update

    As the OP specified in a comment, the users must be sorted by their online status (online first) and then by their usernames (ascending).

    The (updated) query is:

    SELECT u.*, IF(Last_logged_in >= UNIX_TIMESTAMP() - 60, 1, 0) as isOnline;
    FROM users u
    ORDER BY isOnline DESC, username ASC
    LIMIT 20
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘