Answer the question
In order to leave comments, you need to log in
How do views work in MySQL?
MySQL has a view (View) that makes a query with a lot of JOINs, calculations (sum, etc.) and returns the table I need.
Let's say the returned fields are: ID, Num, Name, Price, Discount
The View itself calculates data for all data from the database. But what if I don't need all the data, but, for example, where ID = N;
That is, having made a request, SELECT * FROM MyView WHERE ID = {variable}
I get the result I need. But if I understand correctly, the query in the view will be executed first, and only then, from the result returned by the view, the only record I need will be selected. It turns out that I consider the results for all the data, but I take only one. This is true?
If so, what should be done in such situations? Of course, I can write a separate request in the application - but the requests will be three-story. In addition to this, views are convenient in that they can be used in other queries without rewriting hundreds of times the same formulas for calculating the data I need.
Answer the question
In order to leave comments, you need to log in
A view is like a request template prepared in advance. When you perform a search on some view, you actually only add your own conditions to this template.
Here is a simple view (let's call it `users_online`) that shows users who have been active in the last 15 minutes:
SELECT *
FROM `users` AS `u`
JOIN `activity` AS `a`
ON `a`.`user_id` = `u`.`id`
AND `a`.`modified` >= CURRENT_TIMESTAMP - INTERVAL 15 MINUTE;
SELECT * FROM (
SELECT *
FROM `users` AS `u`
JOIN `activity` AS `a`
ON `a`.`user_id` = `u`.`id`
AND `a`.`modified` >= CURRENT_TIMESTAMP - INTERVAL 15 MINUTE
) AS `users_online`
WHERE `age` > 18;
SELECT * FROM `users` WHERE `online` = 1 AND `age` > 18;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question