Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SELECT on an array of constants

Tags:

mysql

In MySQL, how is it possible to do a SELECT on an array of constant values? Something similar to this:

SELECT ['1', '2', '3'] AS ID;

Where the desired output is:

+-----+
| ID  |
+-----+
| 1   |
| 2   |
| 3   |
like image 768
Daniel Szalay Avatar asked Sep 12 '14 09:09

Daniel Szalay


People also ask

What is an array constant in Excel?

In Excel, an array constant is a way to write an array of literal data in your Excel formulas. Think of it this way, a range of A1:A3 is actually an array of data.

How do you create an array constant?

Create an array constant on the block diagram by combining an array with a valid constant, which can be a numeric, Boolean, string, path, refnum, or cluster constant. The element cannot be another array.

How do you select multiple records?

Press CTRL or SHIFT and click to select multiple records in the Unmerged or On hold tab.

How can constants be used when working with arrays?

You can create an array constant and you can give it a name that can then be used in your formulas. Array constants are a list of values that can be used as arguments in your array formulas. Arrays can be either 1-dimensional or 2-dimensional depending on the number of rows and columns.


1 Answers

You can use joins to generate a series of rows.

SELECT 1 AS ID UNION SELECT 2 UNION SELECT 3

For small amounts of data this works well. Down side is that there is no index to check these on.

A temp table is likely far better for this as at least any SQL that joins against these values can then use indexes.

Another possibility if the values are from a limited pool is to just have a table which contains all possible values and select from it:-

SELECT ID 
FROM all_poss_values
WHERE ID IN (1,2,3)

or using a generated range of values (which again loses the availability of indexes):-

SELECT 1 + units.i + tens.i * 10 AS ID
FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units,
(SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens
WHERE 1 + units.i + tens.i * 10 IN (1,2,3)
like image 165
Kickstart Avatar answered Sep 23 '22 11:09

Kickstart