简体   繁体   中英

Multiple updates query

I've an update query, that updates 2 tables, one of those is duplicated with a different alias. The engine is MySQL. If I run the three queries separately they work ok, but if I put all of them in only one query it seams to fail.

This is the query:

UPDATE
    users AS u1,
    users AS u2,
    customer AS c
SET
    u1.`active` = '1',
    u2.`address` = 'something 234',
    c.`status` = '3'
WHERE
    (u1.`user_name` = 'Tomas'
        AND u1.`user_lastname` = 'Smith'
        AND u1.`user_middle` = 'Nikolas')
    AND (u2.`user_type` = '5'
        AND u2.`user_email` = 'an_email@gmail.com'
        AND u2.`register_date` = 'some_date')
    AND c.`id` = '8';

If I run the queries separately, the users tables update doesn't update any row (that's ok) and the customer updates only one row (that's ok too).

I'm looking forward to do everything in only one query and not in three.

The three queries looks like this:

UPDATE users AS u1 SET u1.`active` = '1' WHERE u1.`user_name` = 'Tomas' AND u1.`user_lastname` = 'Smith' AND u1.`user_middle` = 'Nikolas';

UPDATE users AS u2 SET u2.`address` = 'something 234' WHERE u2.`user_type` = '5' AND u2.`user_email` = 'an_email@gmail.com' AND u2.`register_date` = 'some_date';

UPDATE customer AS c SET c.`status` = '3' WHERE c.`id` = '8';

I want all of them in one query as I show you before. There's no relation between those queries, are just different queries that I want to run all at once to make improvements.

I dunno if it's possible.

Thanks for reading my problem.

Functions like mysql_query (deprecated!) or mysqli::query do not support multiple statements.

You will need something like mysqli::multi_query for that.

I think you can't updates in several tables with one query. The only multiple update command is allowed in one table only more to that here (read completely to speed it up)

Each query seems to have its own WHERE conditions - I don't think combining them all like that will work, since ALL of the conditions would have to be true for it to update each row.

Also, I don't see this giving any where near enough performance improvement to warrant how unmaintable/illogical this code would become. I definitely recommend keeping these as separate queries.

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