简体   繁体   中英

SQL Delete rows based on query from same table?

Given this query :

SELECT cur.`id`
FROM `current` AS cur
LEFT OUTER JOIN (
    SELECT MAX(EndDay_id.id) as id, EndDay_id.server_id
    FROM current as EndDay_id
    GROUP BY server_id, gameday
    ) AS EndDay
ON cur.id = EndDay.id
WHERE EndDay.id IS null

How do I delete the rows from table 'current' whose id field is in the resultset of previous query ?

delete current
where id in (SELECT cur.`id`
FROM `current` AS cur
LEFT OUTER JOIN (
SELECT MAX(EndDay_id.id) as id, EndDay_id.server_id
FROM current as EndDay_id
GROUP BY server_id, gameday
) AS EndDay
ON cur.id = EndDay.id
WHERE EndDay.id IS null)

Try this

DELETE cur FROM `current` AS cur
LEFT OUTER JOIN (
    SELECT MAX(EndDay_id.id) as id, EndDay_id.server_id
    FROM current as EndDay_id
    GROUP BY server_id, gameday
    ) AS EndDay
ON cur.id = EndDay.id
WHERE EndDay.id IS null

I tested it and this should work: http://sqlfiddle.com/#!2/a47c81

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM