V
V
vista1x2015-08-23 16:19:46
MySQL
vista1x, 2015-08-23 16:19:46

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

1 answer(s)
F
Finnish, 2015-08-23
@finnish

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;

When selecting online users over the age of 18, your query will most likely be something like this:
Which for a database is equivalent to:
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;

In each case, the database can optimize the query, and the result may be something else, but the meaning of this does not change and is described in the first sentence of my comment. For example, a simpler representation:
... with your conditions will become:
SELECT * FROM `users` WHERE `online` = 1 AND `age` > 18;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question