Question

I have following tables

report_pre    { id, date}
report_sections   {id,report,data}

I want to delete table fragments with following sql code:-

DELETE
FROM
report_sections
WHERE
report=ANY(
    SELECT 
        rs.report 
    FROM 
        report_sections rs 
    WHERE 
        NOT EXISTS (
            SELECT
                rp.id
            FROM
                report_pre rp
            WHERE
                rp.id=rs.report
        )
)

But I get the message:

#1093 - You can't specify target table 'report_sections' for update in FROM clause

What am I doing wrong? I tried it already different ways, but found no solution so far. Please help.

Was it helpful?

Solution

This may do what you want:

DELETE rs
    FROM report_sections rs LEFT JOIN
         report_pre rp
         on rp.id = rs.report
    WHERE rp.id IS NULL;

This will delete all rows from report_sections that don't have a matching record in report_pre.

I think the error message is pretty clear on your original message. You can work around it by using an additional layer of subqueries. But, it is fun to learn the join method to get around this problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top