mysql – How to Insert into a DB Selected via Another DB in MySQL

insertMySQLselect

I have a table that stores what database should I use for a given device( specified by its IMEI), like this:

imeiDB(
IMEI VARCHAR(15),
db VARCHAR(100));

Let's say I have the database device1(IMEI:123456789123456) is using stored in imeiDB:

123456789123456 | device1db

Supposing I have not selected the database to store the data, how can I select it on the insert into query of my table device1db.table1?

table1(IMEI VARCHAR(15),data VARCHAR(10))

I tried this but it did not work:

INSERT INTO (SELECT db FROM imeiDB where IMEI=123456789123456).table1 (IMEI,data) VALUES (123456789123456,"somestuff")

Any suggestions?

Best Answer

What you need is some Dynamic SQL.

STEP 01 : Retrieve the DB

SET @IMEI = 123456789123456;
SELECT db INTO @db FROM imeiDB WHERE IMEI = @IMEI;

STEP 02 : Create the SQL to do the INSERT into the retrieve DB

SET @sql = CONCAT('INSERT INTO ',@db,'.table1 (IMEI,data) VALUES (',@IMEI,',"somestuff"');
SELECT @sql\G

STEP 03 : Execute the SQL Statement you just created

PREPARE s FROM @sql;
EXECUTE s;
DEALLOCATE PREPARE s;

EPILOGUE

Execute them in that order

SET @IMEI = 123456789123456;
SELECT db INTO @db FROM imeiDB WHERE IMEI = @IMEI;
SET @sql = CONCAT('INSERT INTO ',@db,'.table1 (IMEI,data) VALUES (',@IMEI,',"somestuff"');
PREPARE s FROM @sql;
EXECUTE s;
DEALLOCATE PREPARE s;

GIVE IT A TRY !!!