Should I do single more complex MySQL query or multiple simpler queries with PHP?
For example
Simpler queries:
UPDATE image SET profile = 0 WHERE user_id = 1;
UPDATE image SET profile = 1 WHERE user_id = 1 AND id = 10;
One single more complex query:
UPDATE image
SET profile = CASE id WHEN 10 THEN 1 ELSE 0 END
WHERE user_id = 1;
1: What is fastest and most efficient?
2: What is considered to be best practice, or preferred method?
However, in the context of the question, a single large query will be faster that, let's say -in the worse possible scenario- a SELECT inside a programming loop (no matter the RDBMS used).
With a single query you get everything in one go. With multiple queries you get one thing. Then you ask for another thing and get that. Then you ask for another thing and get that.
MySQL was not designed for running complicated queries against massive data volumes (which requires crunching through a lot of data on a huge scale). MySQL optimizer is quite limited, executing a single query at a time using a single thread.
Database-level aggregation is much faster than executing the same aggregation logic at the application level while looping on large arrays. Using queries involving SQL aggregate functions with the GROUP BY statement allows you to reduce the number of rows returned drastically.
One single query is fastest and most efficient
Besides the IF statement, MySQL also provides an alternative conditional statement called MySQL CASE. The MySQL CASE statement makes the code more readable and efficient. See more details... http://www.mysqltutorial.org/mysql-case-statement/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With