本文介紹了MySQL CTE。使用WITH和INSERT IT會提示語法錯誤的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧!
問題描述
我試圖在mysql8上編寫這個查詢,但它一直告訴我語法錯誤。我該怎么辦?
WITH this_year AS (
SELECT YEAR(CURDATE())
),
max_val AS (
SELECT
IFNULL(MAX(custom_id_counter), 0)
FROM flow_instances AS max_val
WHERE
custom_id_year = YEAR(CURDATE())
)
INSERT INTO flow_instances (
custom_id_year,
custom_id_counter
) VALUES (
this_year,
max_val+1
);
錯誤:
錯誤代碼:1064。您的SQL語法中有一個錯誤;請檢查
與您的MySQL服務(wù)器版本對應(yīng)的手冊
使用NEAR‘INSERT INSERT FLOW_INSTANCES(CUSTOM_ID_Year,
)的語法
Custom_id_Counter)值(‘在第11行
推薦答案
使用insert . . . select
:
INSERT INTO flow_instances (custom_id_year, custom_id_counter)
WITH this_year AS (
SELECT YEAR(CURDATE()) as this_year
),
max_val AS (
SELECT COALESCE(MAX(custom_id_counter), 0) as max_val
FROM flow_instances AS max_val
WHERE custom_id_year = YEAR(CURDATE())
)
SELECT ty.this_year, mv.max_val + 1
FROM this_year ty CROSS JOIN
max_val mv;
您需要引用CTE才能使用它們定義的值。
這篇關(guān)于MySQL CTE。使用WITH和INSERT IT會提示語法錯誤的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,