I want when executing this query
SELECT tabla1.campo1
From tabla1, tabla2
Where tabla1.campo1 = tabla2.campo1
Group By tabla1.campo1;
Which will give me, for example, 600 records, save the 600 records in an array to later use the index of the array (from 1 to 600) as a comparison in another query, as I must use an array and a for loop, but I already investigated and no I find a clear example, I would like to know the following things:
Can it do what I want?
Is it resource efficient?
Is there any better method?
Although MySQL doesn't have a data type
ARRAY
, I think what you want is to use the result of your query later, without having to write it over and over again. This is possible: you can save the result in a temporary table, and use it as many times as you want:Now, if what you need is to assign a number to each record, you can use user variables:
Remember: Temporary tables are only visible to the connection that created them, and are destroyed once the connection that created them is closed.
update
As you can see, I am not using a stored procedure to generate the table you require, but rather I am generating the row numbers you need "on the fly".
How does it work?
In the clause
FROM
I include your two tables, and a subquery (which I callinit
) to initialize the variable@n
. Remember that in SQL the "order of execution" is:FROM
: The server checks that the data sources exist and can be read; In addition, the required relationships are establishedWHERE
: The relevant filters are applied to the data sourcesGROUP BY
: The data is groupedSELECT
: Fields are read and expressions are calculated (including aggregation expressionsHAVING
: Relevant filters are applied to the data after it has been groupedSo, taking advantage of the fact that the first thing that is executed is the
FROM
, I put a variable initialization query (init
) there. The variable@n
is initialized to zero, and each time itSELECT
reads a row, it updates the value of@n
, adding 1 to it.Finally, by creating a temporary table, you guarantee that the row numbers aren't updated every time you run the query (since you're not ordering the values, there's no guarantee that an ordering of the rows will be respected).
Once you run the above queries, you can use these values simply by selecting all rows from the newly created table:
Now I see you're not using any aggregation functions; I think it's easier then to use
SELECT DISTINCT
:Why is "on the fly" better than with a procedure?
If you want to try a stored procedure, consider the following:
AUTO_INCREMENT
in the table definition, you'd want the procedure to store the number instead)For mere economy of keys, you should generate the values "on the fly". On the other hand, by generating the values "on the fly" using temporary variables, you're not really giving the server too much extra work.