php - 关于sql查询php

标签 php mysql sql

我想搜索活跃 session 数超过100的终端,我使用的表是terminal_server_log,因为每个终端都有很多日志,我必须确保“时间戳”是最新的。我尝试了两种方式进行搜索。请注意,对于每个终端,最新时间戳并不相同。

$termquery=mysql_query("select distinct(terminal) from
    terminal_server_log where activesession > 100
    group by terminal order by timestamp limit 1");
while($termres=mysql_fetch_array($termquery)){
        $terms=$termres["terminal"];

    array_push($result, array(
          "terminal" => array(
                "type" => "resource",
                "searchvector" => "/tsmon-dev/api/terminal.php?username=$terms",
                "displayvalue" => $terms
                 )
           )
     );
}

echo (json_encode($result)); 

但是,它不起作用。问题是什么?谢谢!

最佳答案

如果你想获取所有 activesession > 100 的终端,那么使用 limit 1 是没有意义的

从terminal_server_log中选择终端,最大(时间戳),其中activesession > 100按终端分组

它将返回 [terminal, timestamp] 对,其中终端仅具有 activesession>100,并且每条记录的时间戳都是最新的。

如果你想获得一个活跃 session >100且具有最新记录的终端,查询将是:

从terminal_server_log中选择终端,其中activesession > 100 order by timestamp desc limit 1

是的,

please note that the mysql_ constructor is deprecated as of PHP 5.5 //Obsidian Age advised in comments.

已更新

Actually I only want to know the current situation: which terminal's active session is more than 100. I mean, for each terminal, there are a lot of records, if the latest record for this terminal's active session is more than 100, then i choose it

SELECT  a.terminal
FROM    terminal_server_log a
inner join
        (
            SELECT  terminal, MAX(timestamp) timestamp
            FROM    terminal_server_log
            group by terminal
        ) b on (b.terminal=a.terminal and a.timestamp=b.timestamp)
WHERE a.activesession>100

关于php - 关于sql查询php,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45405553/

相关文章:

sql - 如何使用 WHERE x IN 子句为 PreparedStatement 编写 SQL?

c# - 以表格形式查看 XML 数据

php - 担心表格字段太多

php if 和 elseif 语句具有多个/超过 3 个条件

php - 如何使用 Guzzle 6 配置默认查询参数?

mysql - 错误号 150 mySQL

mysql - 更快 LIKE '%XXX'

php - 将一个应用程序连接到另一个应用程序的数据库时出错

php - 将复选框数据从 php 存储到数据库

PHP: Laravel 无法添加外键约束