如何将其转换为普通查询?
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}”
2条答案
按热度按时间92vpleto1#
实际上是MariaDB is compatible with CTEs,但是如果出于某种原因不想处理ctes,可以将其转换为一个子查询:
如果这个查询代替cte生成的查询不适合你,那么这意味着你的初始查询在你的表关系上有一些错误。
wfypjpf42#
再次更新:
它现在为我工作,这里是我的最终代码: