查询错误:错误:ER_PARSE_ERROR:您的SQL语法有错误;查看与您的MySQL相对应的手册

时间:2019-02-05 05:57:39

标签: mysql sql

我正在尝试使用下面的查询联接两个表。

(SELECT CustomerName, OrderDate,
LAG(OrderDate,1) OVER(ORDER BY OrderDate DESC) as Previous_Order_Date
FROM Table1) as t1
INNER JOIN  (SELECT CustomerName, MAX(OrderDate) as Latest_Order_date
             FROM Table1
             GROUP BY CustomerName) as t2
ON t1.CustomerName = t2.CustomerName AND t1.OrderDate = t2.Latest_Order_date

但是我得到以下错误:

  

查询错误:错误:ER_PARSE_ERROR:您的SQL语法有错误;检查与您的MySQL服务器版本相对应的手册以获取正确的语法,以在第3行“ as t1 INNER JOIN(SELECT CustomerName,MAX(OrderDate)as Latest_Order_date)”附近使用

db-fiddle

3 个答案:

答案 0 :(得分:1)

您缺少外部选择子句:

SELECT
    t1.CustomerName,
    t1.Previous_Order_Date,
    t2.Latest_Order_date
FROM
(
    SELECT CustomerName, OrderDate,
        LAG(OrderDate,1) OVER(ORDER BY OrderDate DESC) AS Previous_Order_Date
    FROM Table1
) AS t1
INNER JOIN
(
    SELECT CustomerName, MAX(OrderDate) AS Latest_Order_date
    FROM Table1
    GROUP BY CustomerName
) AS t2
    ON t1.CustomerName = t2.CustomerName AND t1.OrderDate = t2.Latest_Order_date;

但是实际上您可能能够简化查询,甚至不使用任何联接:

SELECT
    t.CustomerName,
    t.Previous_Order_Date,
    t.Latest_Order_date
FROM
(
    SELECT CustomerName, OrderDate,
        LAG(OrderDate,1) OVER(ORDER BY OrderDate DESC) AS Previous_Order_Date,
        MAX(OrderDate) OVER (PARTITION BY CustomerName) AS Latest_Order_date
    FROM Table1
) t
WHERE
    t.Previous_Order_Date = t.Latest_Order_date;

如果在您的联接中传递的每一行都匹配一个且只有一条记录,这将是正确的。

请注意,如果子查询之间的内容是UNION而不是join,则当前的语法实际上在MySQL上有效。也就是说,以下是有效的语法:

(SELECT CustomerName, OrderDate FROM Table1)
UNION
(SELECT CustomerName, OrderDate FROM Table1)

答案 1 :(得分:1)

您需要添加一个零件,例如

SELECT t1.CustomerName, t1.Previous_Order_Date, t2.Latest_Order_date
  FROM

对于查询的上述部分,为:

SELECT t1.CustomerName, t1.Previous_Order_Date, t2.Latest_Order_date
  FROM (SELECT CustomerName,
               OrderDate,
               LAG(OrderDate, 1) OVER(ORDER BY OrderDate DESC) as Previous_Order_Date
          FROM Table1) as t1
 INNER JOIN (SELECT CustomerName, MAX(OrderDate) as Latest_Order_date
               FROM Table1
              GROUP BY CustomerName) as t2
    ON t1.CustomerName = t2.CustomerName
   AND t1.OrderDate = t2.Latest_Order_date

答案 2 :(得分:0)

您没有主选择语句。

尝试类似的东西:

SELECT *
FROM (SELECT CustomerName, OrderDate,
LAG(OrderDate,1) OVER(ORDER BY OrderDate DESC) as Previous_Order_Date
FROM Table1) as t1
INNER JOIN  (SELECT CustomerName, MAX(OrderDate) as Latest_Order_date
             FROM Table1
             GROUP BY CustomerName) as t2
ON t1.CustomerName = t2.CustomerName AND t1.OrderDate = t2.Latest_Order_date

MySQL select需要以下格式的查询:

SELECT *
FROM table1 AS t1
JOIN table2 AS t2
  ON t1.id = t2.id
JOIN (SELECT id, value FROM table3) as t3
  on t3.id = t2.id
WHERE t3.value IS NOT NULL;