mariadb 如何将CTE转换为普通查询?

fivyi3re  于 2022-11-08  发布在  其他
关注(0)|答案(2)|浏览(148)

如何将其转换为普通查询?

WITH cte AS (
    SELECT agentID, 
           SUM(bonus > 0) OVER (PARTITION BY agentID 
                                ORDER BY `year` * 12 + `month`
                                RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) flag
    FROM test
)
SELECT agentID
FROM cte
WHERE flag = 3;

我需要转换这个,因为我认为mariadb是不兼容cte。我不是真的熟悉cte太,我不知道如何打破这在php中正常的sql查询。
最新消息:
我试着这么做是为了进行CTE

<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "sample_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->query("SELECT agentID, bonus FROM (WITH cte AS (
    SELECT DISTINCT agentID, 
           SUM(bonus > 0) OVER (PARTITION BY agentID 
                                ORDER BY `year` * 12 + `month`
                                RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) flag
    FROM sample_tbl
)) where agentID = '10710' && flag = 3");

    if($stmt->num_rows > 0){
        echo "You are elligible to take a course!";
    } else{
           echo "You are not elligible to take a course!";
        }

?>

但结果表明,它并不起作用,
“致命错误:未捕获的mysqli_sql_异常错误:您的SQL语法中有错误;查看与您的MariaDB服务器版本对应的手册,以了解使用near ')的正确语法,其中agentID = '10710' && flag = 3'位于C:\xampp\htdocs\try\index.php中的第7行:16堆栈跟踪:(16):请输入您的密码,如果您有任何问题,请联系我们。在第16行的C:\xampp\htdocs\try\index.php中抛出了查询('SELECT代理ID,...')#1 {main}”

92vpleto

92vpleto1#

实际上是MariaDB is compatible with CTEs,但是如果出于某种原因不想处理ctes,可以将其转换为一个子查询:

SELECT agentID
FROM (
    SELECT agentID, 
           SUM(bonus > 0) OVER (PARTITION BY agentID 
                                ORDER BY `year` * 12 + `month`
                                RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) flag
    FROM test ) agents_with_summed_bonus
WHERE flag = 3;

如果这个查询代替cte生成的查询不适合你,那么这意味着你的初始查询在你的表关系上有一些错误。

wfypjpf4

wfypjpf42#

再次更新:
它现在为我工作,这里是我的最终代码:

<?php
$servername = "localhost";
$username = "root";
$password = "";
$db = "sample_db";

// Create connection
$conn = new mysqli($servername, $username, $password, $db);

// Check connection
if ($conn->connect_error) {
  die("Connection failed: " . $conn->connect_error);
}

$stmt = $conn->query("SELECT DISTINCT agentID FROM (SELECT DISTINCT agentID, 
SUM(bonus > 0) OVER (PARTITION BY agentID 
                     ORDER BY `year` * 12 + `month`
                     RANGE BETWEEN 2 PRECEDING AND CURRENT ROW) flag from sample_tbl) as cte where agentID = '61599' && flag = 3");

    if($stmt->num_rows > 0){
        echo "You are elligible to take a course!";
    } else{
           echo "You are not elligible to take a course!";
        }

?>

相关问题