开发者

How to combine two unrelated SQL queries

开发者 https://www.devze.com 2023-04-11 14:26 出处:网络
Let\'s say I have two SQL queries: INSERT INTO tableA VALUES (\'\', \'mike\', \'21\') DELETE FROM tableB WHERE name = \'john\'

Let's say I have two SQL queries:

INSERT INTO tableA VALUES ('', 'mike', '21')

DELETE FROM tableB WHERE name = 'john'

开发者_StackOverflowAnd I want to execute them at the same time. How do I do that? I know that UNION only works for SELECT statements, so it's useless in this case.


You create a transaction.

http://dev.mysql.com/doc/refman/5.5/en/commit.html

START TRANSACTION;
  INSERT INTO tableA VALUES ('', 'mike', '21');
  DELETE FROM tableB WHERE name = 'john';
COMMIT;


Write a stored procedure that encapsulates these statements and call that from your application.


Put all statements in a stored procedure and call that procedure instead.


You can't execute them both at exactly the same time, but I'm guessing you're asking this because you only want to run the second query if the first one succeeds. This can be achieved by using transactions. There are some good examples is this question.


You need to look into using transactions. This is the A (atomicity) in the ACID properties that guarantee transactional integrity in databases, meaning that either all of a transaction will happen or none of it will.

Check out the latest docs for a description of how this works. Basically, it's:

start transaction
do your first operation
do your second operation
commit

And, with proper isolation, the changes won't be visible to the outside world until the commit is done.

0

精彩评论

暂无评论...
验证码 换一张
取 消