Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string as mysql table name

Tags:

sql

mysql

The query it self will explain where i'm stuck at, i'm unable to change the schema, is there any way to use the table name that i get from the if statement and continue to query ?

SELECT *,IF(user.type = 1,"staff","admin") as "table" FROM user WHERE "table".user_id = user.id

http://sqlfiddle.com/#!9/842be4/1

I tried setting a variable, still didn't work out. any ideas ? Thank you.

like image 696
bro_php Avatar asked Mar 24 '26 06:03

bro_php


1 Answers

You want to have a dynamic query like

SET @table_name = (SELECT IF(user.type = 1,"staff","admin") FROM `user`);

SET @t1 =CONCAT("SELECT * FROM menu LEFT JOIN ", @table_name," ON ", @table_name,".user_id = user.id");
 PREPARE stmt FROM @t1;
 EXECUTE stmt;
 DEALLOCATE PREPARE stmt;
like image 105
Rahul Avatar answered Mar 26 '26 20:03

Rahul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!