Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I simulate an array variable in MySQL?

It appears that MySQL doesn't have array variables. What should I use instead?


There seem to be two alternatives suggested: A set-type scalar and temporary tables. The question I linked to suggests the former. But is it good practice to use these instead of array variables? Alternatively, if I go with sets, what would be the set-based idiom equivalent to foreach?

like image 445
einpoklum Avatar asked Aug 29 '12 11:08

einpoklum


People also ask

Is there an array datatype in MySQL?

MySQL doesn't have an array data type. This is a fundamental problem in architectures where storing denormalized rows is a requirement, for example, where MySQL is (also) used for data warehousing.

How do I find an array in MySQL?

Data can be fetched from MySQL tables by executing SQL SELECT statement through PHP function mysql_query. You have several options to fetch data from MySQL. The most frequently used option is to use function mysql_fetch_array(). This function returns row as an associative array, a numeric array, or both.

How do I create a variable in MySQL?

MySQL variable assignment There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.

Can MySQL return an array?

Mysql doesn't have a Fetch array function. mysql_fetch_array is a PHP function that will allow you to access data stored in the result returned from the TRUE mysql_query if u want to know what is returned when you used the mysql_query function to query a Mysql database.


2 Answers

Well, I've been using temporary tables instead of array variables. Not the greatest solution, but it works.

Note that you don't need to formally define their fields, just create them using a SELECT:

DROP TEMPORARY TABLE IF EXISTS my_temp_table; CREATE TEMPORARY TABLE my_temp_table     SELECT first_name FROM people WHERE last_name = 'Smith'; 

(See also Create temporary table from select statement without using Create Table.)

like image 58
einpoklum Avatar answered Nov 15 '22 16:11

einpoklum


You can achieve this in MySQL using WHILE loop:

SET @myArrayOfValue = '2,5,2,23,6,';  WHILE (LOCATE(',', @myArrayOfValue) > 0) DO     SET @value = ELT(1, @myArrayOfValue);     SET @myArrayOfValue= SUBSTRING(@myArrayOfValue, LOCATE(',',@myArrayOfValue) + 1);      INSERT INTO `EXEMPLE` VALUES(@value, 'hello'); END WHILE; 

EDIT: Alternatively you can do it using UNION ALL:

INSERT INTO `EXEMPLE` (  `value`, `message` ) (  SELECT 2 AS `value`, 'hello' AS `message`  UNION ALL  SELECT 5 AS `value`, 'hello' AS `message`  UNION ALL  SELECT 2 AS `value`, 'hello' AS `message`  UNION ALL  ... ); 
like image 41
Omesh Avatar answered Nov 15 '22 18:11

Omesh