查看与您的 MariaDB 服务器版本对应的手册,了解要使用的正确语法

Check the manual the corresponds to your MariaDB server version for the right syntax to use

我正在尝试制作 sql 语法:

UPDATE `%s`
JOIN (WITH t2 AS
(
SELECT LAG(storymain_id,1) OVER (ORDER BY storymain_id) AS lg, `%s`.* 
FROM `%s`
)
SELECT t2.*,
1 + SUM(CASE WHEN COALESCE(lg,storymain_id) = storymain_id THEN 0 ELSE 1 END ) 
OVER (ORDER BY storymain_id) AS new_id
FROM t2 ) t2
ON `%s`.storymain_id = t2.storymain_id SET `%s`.storymain_id = t2.new_id;

在我的 maria-db 服务器上,版本是:

mysql  Ver 15.1 Distrib 10.1.44-MariaDB, for debian-linux-gnu (x86_64) using readline 5.2

我在 运行 时遇到错误:

SQLSTATE[42000]:
Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that 
corresponds to your MariaDB Server version for the right syntax to use near 't2 AS\r\n\t\t\t\t 
(\r\n\t\t\t\t\tSELECT LAG(storymain_id, 1) OVER (ORDER BY storymain_id) AS' at line ~.

我需要让它工作,但我不知道如何更改语法..

感谢您的帮助...

我只是将 cte 替换为正常派生的 table。您没有在查询中只使用一次 cte,所以这并不重要:

update `%s`
join (
    select 
        t2.*,
        1 + sum(case when coalesce(lg,storymain_id) = storymain_id then 0 else 1 end) 
            over (order by storymain_id) as new_id
    from (
        select 
            lag(storymain_id,1) over (order by storymain_id) as lg, 
            `%s`.* 
        from `%s`
    ) t2
) t2
on `%s`.storymain_id = t2.storymain_id 
set `%s`.storymain_id = t2.new_id;

否则,MySQL 需要 with 语句开头的子句:

with t2 as (
    select 
        lag(storymain_id,1) over (order by storymain_id) as lg, 
        `%s`.* 
    from `%s`
)
update `%s`
join (
    select 
        t2.*,
        1 + sum(case when coalesce(lg,storymain_id) = storymain_id then 0 else 1 end) 
            over (order by storymain_id) as new_id
    from t2
) t
on `%s`.storymain_id = t.storymain_id 
set `%s`.storymain_id = t.new_id;

Reference:

A WITH clause is permitted in these contexts:

  • At the beginning of SELECT, UPDATE, and DELETE statements.

    WITH ... SELECT ...

    WITH ... UPDATE ...

    WITH ... DELETE ...