3

i need in one query use select, insert, delete and update.

(I need copy data from old table in to new, then delete old, and update another).

Insert and select (copy function I was able to, but now i have problem)

I have this query:

INSERT INTO news_n (id, data)
    SELECT (id, data)
    FROM news
    WHERE id > 21

Thanks

1
  • What's the error? You can not use the same table to perform multiple operations, i.e. SELECT with UPDATE or DELETE. Commented Nov 3, 2010 at 16:20

4 Answers 4

7

You can't do it all in one query, but you can do it all in one transaction if you are using a transactional store engine (like InnoDB). This might be what you want, but it's hard to tell only using the information you provided in your question.

START TRANSACTION;

INSERT...;
DELETE...
UPDATE...;

COMMIT;
Sign up to request clarification or add additional context in comments.

Comments

2

MySQL does not support MERGE, so you'll have to do it in two queries:

INSERT
INTO    news_n (id, data)
SELECT  id, data
FROM    news
WHERE   id > 21
ON DUPLICATE KEY UPDATE
SET     data = news.data

DELETE
FROM    news_n
WHERE   id NOT IN
        (
        SELECT  id
        FROM    news
        WHERE   id > 21
        )

, provided you have PRIMARY KEY (id) in both tables.

Comments

2

In one query i dont think its possible.

You can try writing a Stored Procedure and using Triggers you may achieve that

Comments

0

You can't combine Select/Update/etc into one query. You will have to write separate queries for each operation you intend to complete.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.