我有以下查询可在phpMyAdmin中使用
SELECT CONCAT("'",GROUP_CONCAT( fence_id SEPARATOR "','" ),"'") AS fence_ids
FROM asset_fence af
INNER JOIN assets a ON a.vehicle_id = af.vehicle_id
WHERE a.client_id=1
但是相同的查询给我存储过程错误
错误是:
您的SQL语法有错误;检查与您的MariaDB服务器版本相对应的手册,以在第8行的'@fence_ids = SELECT CONCAT(“',, GROUP_CONCAT(fence_id SEPARATOR”','“),”'“)AS'附近使用正确的语法>
存储过程为
DELIMITER $$
CREATE PROCEDURE `prcDeleteClient`(IN `f_client_id` INT, OUT AROWS INT)
BEGIN
START TRANSACTION;
@fence_ids = SELECT CONCAT("'",GROUP_CONCAT( fence_id SEPARATOR "','" ),"'") AS fence_ids FROM asset_fence af INNER JOIN assets a ON a.vehicle_id = af.vehicle_id WHERE a.client_id=f_client_id
DELETE
asset_fence,
geo_fence
FROM
geo_fence gf INNER JOIN asset_fence af ON gf.fence_id = af.fence_id
WHERE
af.fence_id IN (@fence_ids)
DELETE
client,
assets,
asset_movement
FROM
asset_movement am INNER JOIN assets a ON am.vehicle_id = a.vehicle_id
assets a INNER JOIN client c ON a.client_id = c.client_id
WHERE
c.client_id=f_client_id
SET @AROWS = ROW_COUNT();
SELECT @AROWS as AROWS;
COMMIT;
END $$
DELIMITER ;
更新的过程是
DELIMITER $$
CREATE PROCEDURE `prcDeleteClient`(IN `f_client_id` INT, OUT AROWS INT)
BEGIN
START TRANSACTION;
DELETE
af,
gf
FROM
geo_fence gf
INNER JOIN asset_fence af ON gf.fence_id = af.fence_id
INNER JOIN assets a ON a.vehicle_id = af.vehicle_id
WHERE
a.client_id=f_client_id;
DELETE
c,
a,
am
FROM
asset_movement am INNER JOIN assets a ON am.vehicle_id = a.vehicle_id
assets a INNER JOIN clients c ON a.client_id = c.client_id
WHERE
c.client_id=f_client_id;
SELECT ROW_COUNT() AS AROWS;
COMMIT;
END $$
DELIMITER ;
错误是:MULTI DELETE中的未知表'c'
什么是错误,我该如何纠正?
最好的问候
答案 0 :(得分:0)
您正在设置一个值,因此不需要列别名...
删除AS fence_ids
SELECT CONCAT("'", GROUP_CONCAT( af.fence_id SEPARATOR "','" ),"'")
FROM asset_fence af
INNER JOIN assets a ON a.vehicle_id = af.vehicle_id
WHERE a.client_id=1
并且您还错过了每次删除的命令终止器
DELETE
asset_fence,
geo_fence
FROM
geo_fence gf INNER JOIN asset_fence af ON gf.fence_id = af.fence_id
WHERE
af.fence_id IN (@fence_ids);
DELETE
client,
assets,
asset_movement
FROM
asset_movement am INNER JOIN assets a ON am.vehicle_id = a.vehicle_id
assets a INNER JOIN client c ON a.client_id = c.client_id
WHERE
c.client_id=f_client_id;
答案 1 :(得分:0)
首先,您分配变量的语法是错误的,它需要在变量名称前使用SET
命令。
第二,如果要将SELECT
查询的结果用作值,则必须在其周围加上括号:
SET @fence_ids = (SELECT ...);
第三,当您使用时:
WHERE af.fence_id IN (@fence_ids)
它将@fence_ids
视为单个ID,而不是ID列表。所以这等效于:
WHERE af.fence_id = @fence_ids
如果要搜索逗号分隔列表中的内容,则需要使用FIND_IN_SET
:
WHERE FIND_IN_SET(af.fence_id, @fence_ids)
您也不应在GROUP_CONCAT()
中的值周围加上引号。
但是您首先不应该使用GROUP_CONCAT
,而应该与返回所有所需ID的查询一起使用。
DELETE
af,
gf
FROM
geo_fence gf
INNER JOIN asset_fence af ON gf.fence_id = af.fence_id
INNER JOIN assets a ON a.vehicle_id = af.vehicle_id
WHERE a.client_id=f_client_id;
您无需在两个语句中执行此操作:
SET @AROWS = ROW_COUNT();
SELECT @AROWS as AROWS;
您可以这样做:
SELECT ROW_COUNT() AS AROWS;