Mysql
 sql >> Database >  >> RDS >> Mysql

Inserisci più record in SQL dove i valori sono tutte combinazioni di intervalli definiti in una singola query

Prova in questo modo:

INSERT INTO table1( userID,credID,time)
SELECT x,y,'2013-12-12' 
FROM (
  SELECT 1 As x union
  SELECT 2 union
  SELECT 3 union
  SELECT 4 union
  SELECT 5
) xx
CROSS JOIN (
  SELECT 10 As y union
  SELECT 11 union
  SELECT 12 union
  SELECT 13 union
  SELECT 15 union
  SELECT 16 union
  SELECT 17 union
  SELECT 18 union
  SELECT 19 union
  SELECT 20
) yy

Demo:http://www.sqlfiddle.com/#!2/8398d/1

EDIT.

Se questi due elenchi di numeri sono densi, c'è un altro trucco con la tabella dei numeri:

CREATE TABLE numbers( x int primary key auto_increment );

INSERT INTO numbers
SELECT null FROM information_schema.columns
LIMIT 100;

CREATE TABLE   table2
  (userID int,credID int,time date);

INSERT INTO table2( userID,credID,time)
SELECT n1.x,n2.x,'2013-12-12' 
FROM numbers n1
CROSS JOIN numbers n2
WHERE n1.x BETWEEN 1 AND 5
  AND n2.x BETWEEN 10 AND 20
;

demo:http://www.sqlfiddle.com/#!9/e121d/1

EDIT.

C'è un altro trucco con la tabella dei numeri.
Se vuoi passare questi due elenchi come stringhe separate da virgole, prova questa query:

CREATE TABLE numbers( x int primary key auto_increment );

INSERT INTO numbers
SELECT null FROM information_schema.columns
LIMIT 100;

CREATE TABLE   table1
  (userID int,credID int,time date);

INSERT INTO table1( userID,credID,time)
SELECT xx,yy,'2013-12-12' 
FROM (
        SELECT reverse( if( locate(',',reverse(SUBSTRING_INDEX( y, ',', x ))) > 0,
                          substr( reverse(SUBSTRING_INDEX( y, ',', x )), 1, locate(',',reverse(SUBSTRING_INDEX( y, ',', x ))) -1 ),
                          reverse(SUBSTRING_INDEX( y, ',', x ))
                     )) AS xx
        FROM (  select '1,22,333,44,51,656'  y ) q
        JOIN numbers n
        ON n.x <= length( y ) - length( replace( y, ',','')) + 1
) q1
CROSS JOIN
(
        SELECT reverse( if( locate(',',reverse(SUBSTRING_INDEX( y, ',', x ))) > 0,
                          substr( reverse(SUBSTRING_INDEX( y, ',', x )), 1, locate(',',reverse(SUBSTRING_INDEX( y, ',', x ))) -1 ),
                          reverse(SUBSTRING_INDEX( y, ',', x ))
                     )) AS yy
        FROM (  select '111,222,3333,444,54,656'  y ) q
        JOIN numbers n
        ON n.x <= length( y ) - length( replace( y, ',','')) + 1
) q2
;

Demo --> http://www.sqlfiddle.com/#!9/83c86 /1