Suppose I have a table T
with 3 columns like this:
x | y | z
---------
I also have PHP arrays of variable lengths $x
, $y
and $z
. Let's say for the purpose of illustration that $x = array("A1", "A2")
, $y = array("B1", "B2")
and $z = array("C1", "C2")
.
What the best way to insert into T
all combinations of $x
, $y
and $z
, where the value of each column in each row is taken from the array with the same name? Thus, in my example, if T
was empty beforehand, it should look like this after this operation:
x | y | z
-------------
A1 B1 C1
A1 B2 C1
A1 B1 C2
A1 B2 C2
A2 B1 C1
A2 B2 C1
A2 B1 C2
A2 B2 C2
Again, the length of each array is not fixed in advance and needn't be the same for all of them, so the solution can't assume a specific length for those arrays.
One way to do that is to create a two-dimensional array in PHP that contains all the combinations, use implode
to generate the VALUES
clause of the INSERT INTO
statement and execute the resulting query, but I would be surprised if there wasn't a way to do this entirely in SQL and if this weren't more efficient. To be honest, performance isn't really an issue for what I'm doing (because there aren't going to be more than a few hundreds combinations at most in each case), but I'm still curious.
EDIT: Based on the replies, it seems I wasn't clear enough about what I was asking for, so let me elaborate. I know how to prepare one or several SQL queries to insert all the possible combinations into T
by looping over the arrays in PHP. But what I would like to know is how to write a SQL query based on the inputs in the PHP arrays that will generate the cartesian product and insert that product into T
, which I'm guessing would be more efficient because presumably MySQL is going to generate the cartesian product faster than I could in PHP.