right语法

x6yk4ghg  于 2021-07-27  发布在  Java
关注(0)|答案(3)|浏览(331)

当我尝试使用order by asc和limit=2从表中删除一些行(从联接表中获得的行)时(例如:如果我获得10条记录,则需要删除前2条记录)。
但是得到错误
sql语法有错误;检查与您的mariadb服务器版本相对应的手册,以获得正确的语法,以便在第9行的“order by sales\u flat\u quote.entity\u id asc limit 2”附近使用
下面是我的代码:

DELETE table1,table2,table3
FROM table1
LEFT JOIN table2 on table1.entity_id=table2.quote_id
LEFT JOIN table3 on table1.entity_id=table3.quote_id
WHERE table1.entity_id <= 101
ORDER BY table1.entity_id ASC LIMIT 2;
cuxqih21

cuxqih211#

您正在执行多表删除操作,文档说明如下:
不能在多表删除中使用order by或limit。
一些解决方法最终可以通过嵌套选择实现。请勾选类似问题的答案。

zlwx9yxi

zlwx9yxi2#

如果临时表是可以接受的,你可以尝试这样的东西。不是极好的,而是直接的解决方案。

CREATE TEMPORARY TABLE TempToBeDeleted (
     id_table1 INT NOT NULL
   , id_table2 INT NOT NULL 
   , id_table3 INT NOT NULL 
);

INSERT INTO (id_table1, id_table2, id_table3)
SELECT DISTINCT table1.primary_key, table2.primary_key, table3.primary_key
FROM 
    table1
    LEFT JOIN table2 ON table1.entity_id = table2.quote_id
    LEFT JOIN table3 ON table1.entity_id = table3.quote_id
WHERE table1.entity_id <= 101
ORDER BY table1.entity_id ASC LIMIT 2;

DELETE FROM table1, table2, table3
FROM
    TempToBeDeleted
    INNER JOIN table1 ON TempToBeDeleted.id_table1 = table1.primary_key
    INNER JOIN table2 ON TempToBeDeleted.id_table2 = table2.primary_key
    INNER JOIN table3 ON TempToBeDeleted.id_table3 = table3.primary_key
;

DROP TABLE TempToBeDeleted;
5vf7fwbs

5vf7fwbs3#

解决方案:

DELETE table1,table2,table3
FROM table1
INNER JOIN (
            SELECT entity_id 
            FROM table1
            WHERE entity_id<= 101
            ORDER BY entity_id ASC
            LIMIT 2
           ) sub1
ON table1.entity_id=sub1.entity_id
LEFT JOIN table2 ON table2.quote_id = table1.entity_id
LEFT JOIN table3 ON table1.entity_id = table3.quote_id

相关问题