MySQL查询适用于mysqlworkbench,但不适用于php环境

时间:2018-09-19 11:29:54

标签: php mysql

我有一个查询可以完美地在MySQL 5.6版本的MySQL工作台程序下运行,但是当我尝试在PHP环境中测试相同的查询时,出现以下错误:

{
  "code": 500,
  "response": {
    "error": {
      "description": "Query error",
      "error": {
        "errorInfo": [
          "42000",
          1064,
          "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')t1 HAVING price > 0 AND price < 804' at line 1"
        ]
      },
      "query": null
    }
  }
}

查询是这个:

SELECT * FROM(
   SELECT t.id, 
          t.user_id , 
          t.invoice_num, 
          t.registration, 
          SUM(t.price) as price
   FROM t_0 t 
   WHERE t.brandid=587
   GROUP BY t.invoice_num)t1 
   HAVING price > 0 AND price < 12
   ORDER BY id DESC LIMIT 100 OFFSET 0;

在PHP环境中,我只是使用PDO连接以这种方式执行查询:

$test_query = "here the query that I have";
$result = $con->query($test_query)->fetchAll(PDO::FETCH_ASSOC);

有人可以向我解释什么可能导致问题吗? 在我看来,语法似乎非常正确。

1 个答案:

答案 0 :(得分:1)

尝试通过将查询更改为几乎可以在任何数据库中运行的查询吗?
(几乎是因为LIMIT可以是特定于数据库的。例如,MS SQL Server使用TOP来代替)

SELECT 
 MAX(t.id) AS id, 
 MAX(t.user_id) AS user_id, 
 t.invoice_num, 
 MAX(t.registration) AS registration, 
 SUM(t.price) as price
FROM t_0 t 
WHERE t.brandid = 587
GROUP BY t.invoice_num
HAVING SUM(t.price) BETWEEN 1 AND 11
ORDER BY id DESC 
LIMIT 100 OFFSET 0