简体   繁体   English

如何获取第X个最新的SQL查询

[英]How to get the X'th most recent SQL query

I'm using the google charts API to create a graph. 我正在使用Google Charts API创建图形。 I have 48 data points, a point for every 30 minutes in a day. 我有48个数据点,一天中每30分钟就有一个数据点。 My php script runs every 15 seconds and saves the calculated Bitcoin Price to a database. 我的php脚本每15秒运行一次,并将计算出的比特币价格保存到数据库中。 Right now to get the most recent price from the database, I am using this code. 现在,要从数据库中获取最新价格,我正在使用此代码。

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

$sql = "SELECT priceLBTC FROM prices ORDER BY id DESC LIMIT 1";
$result = $conn->query($sql);
$bitcoinPrice = 0;
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $bitcoinPrice = round($row["priceLBTC"], 2);
    }
} else {
    echo "0 results";
}

    $sql2 = "SELECT priceLBTC FROM prices ORDER BY id DESC LIMIT 5760";
    $result2 = $conn->query($sql);
    $bitcoinPriceArr = array();
    if ($result->num_rows > 0) {
        // output data of each row
        $i=-1;
        while($row = $result->fetch_assoc()) {
            $i++;
            if ($i%120) continue;

            $bitcoinPriceArr[] = round($row["priceLBTC"], 2);
        }
    } else {
        echo "0 results";
    }


$conn->close();
?>

So the first data point on the graph should be the most recent price, which is $bitcoinPrice, and then the 47 following data points should be the 120 rows before one another. 因此,图表上的第一个数据点应该是最近的价格,即$ bitcoinPrice,然后后面的47个数据点应该是彼此之前的120行。 ex: the id of the next data point is ((row of the most recent price) - 120)). 例如:下一个数据点的ID为((最近价格的行)-120)。 (php script runs every 15 seconds, so 4 times a minute * 30 minutes = 120 times every 30 minutes) (php脚本每15秒运行一次,因此每分钟4次* 30分钟=每30分钟120次)

Is there an easier way to get all that data and put it into the chart without creating 47 other variables and querying them individually? 有没有更简单的方法来获取所有数据并将其放入图表中,而无需创建其他47个变量并单独查询它们?

Here is the relevant google chart javascript 这是相关的谷歌图表JavaScript

function drawAxisTickColors() {
      var data = new google.visualization.DataTable();
      data.addColumn('number', 'X');
      data.addColumn('number', 'Price');

            data.addRows([
    [0, 0],    [1, 10],   [2, <?php echo $bitcoinPriceArr[0]; ?>],  [3, 17],   [4, 18],  [5, 9],
    [6, 11],   [7, 27],  [8, 33],  [9, 40],  [10, 32], [11, 35], [12, 35], [13, 35], [14, 35], [15, 35], [16, 35], [17, 35], [18, 35], [19, 35], [20, 35], [21, 35], [22, 35], [23, 35],
    [24, 5], [25, 5], [26, 5], [27, 5], [28, 5], [29, 5], [30, 5], [31, 5], [32, 5], [33, 5], [34, 5], [35, 5], [36, 5], [37, 5], [38, 5], [39, 5], [40, 31], [41, 320], [42, 315], [43, 305],
    [44, 299], [45, 309], [46, 300], [47, <?php echo $bitcoinPrice; ?>]
  ]);

Please check the forum before just posting a question. 在发布问题之前,请检查论坛。

This is basically explained here: How do you select every n-th row from mysql 基本上在这里解释: 如何从mysql中选择第n行

Applied to your usecase that would be something like this: 应用于您的用例将是这样的:

SELECT * 
FROM ( 
    SELECT 
        @row := @row +1 AS rownum, priceLBTC 
    FROM ( 
        SELECT @row :=0) r, prices 
    ) ranked 
WHERE rownum % [120] = 1

An easier - and maybe even more performant - way though, would be just getting all of the data and cherry pick the points you need with PHP. 不过,一种更简单(甚至可能更高的性能)的方式是,获取所有数据,并从PHP中选择您需要的要点。

$sql = "SELECT priceLBTC FROM prices ORDER BY id DESC LIMIT 5760";
$result = $conn->query($sql);
$bitcoinPrice = array();
if ($result->num_rows > 0) {
    // output data of each row
    $i=-1;
    while($row = $result->fetch_assoc()) {
        $i++;
        if ($i%120) continue;

        $bitcoinPrice[] = round($row["priceLBTC"], 2);
    }
} else {
    echo "0 results";
}


$conn->close();

What happens is: 发生的是:

  • Limit is set to 48 times 120 requests (5760: the maximum for 24 hours) 限制设置为48个120请求(5760:24小时的最大值)
  • $bitcoinPrice should be an array , since it needs to hold a couple of values $bitcoinPrice应该是一个array ,因为它需要保存几个值
  • $i=0 after the first iteration 第一次迭代后$i=0
  • From there on, only data points are picked for which $i leaves no remainder after division by 120 从那里开始,仅选择$i除以120后没有余数的数据点

Even better would be to get all queried results at once via mysqli::fetch_all and build the $bitcoinPrice array by only getting every 120th entry. 更好的办法是通过mysqli::fetch_all一次获得所有查询的结果,并仅通过获取第120个条目来构建$bitcoinPrice数组。 This way you would not have to loop through 119 data points just to get the one you need. 这样,您就不必遍历119个数据点即可获得所需的数据点。

ADD: 加:

You turn a php variable into something usable in javscript with json_encode($bitcoinPriceArr) . 您可以使用json_encode($bitcoinPriceArr)将php变量转换为可在javscript中使用的变量。 If you echo the result of that in an javascript assignemnt you will end up with a javascript array: 如果在javascript分配中回显该结果,则将以javascript数组结尾:

var bitcoinPrizes = <?php echo json_encode($bitcoinPriceArr); ?>;

With that you can build your chart: 这样,您可以构建图表:

var rows=[];

for (var i in bitcoinPrizes ){
    rows.push([i, bitcoinPrizes [i]]);
}

data.addRows($rows);

I assume you could also do: 我想你也可以做:

for (var i in bitcoinPrizes ){
    data.addRows([[i, bitcoinPrizes [i]]);
}

But I am not entirely sure there. 但是我不确定在那里。

Pleae keep in mind that this is no place to get your whole tasks sorted out and solved. 请记住,这不是将所有任务整理和解决的地方。 Hire a developer for that. 为此雇用一名开发人员。 If you have a specific question or run into a concrete problem, you may ask for help here. 如果您有特定问题或遇到具体问题,可以在这里寻求帮助。 But it is still up to you to learn the very basics of the languages and technologies you use. 但是,仍然需要您学习所使用语言和技术的基础知识。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM