簡體   English   中英

sql從列中描述的表名稱中選擇

[英]sql select from table name described in a column

我想從一個具有另一個表中描述的表名的sql表中選擇。

SELECT * 
FROM first_table t1 
WHERE EXISTS (SELECT * FROM t1.other_table t2 WHERE t1.other_table_id = t2.id)

找不到解決方案!

感謝任何幫助。

您可以在查詢中使用動態變量:

SET @table := (select tableName from test limit 1);
set @qry1:= concat('select * from ',@table);
prepare stmt from @qry1 ;
execute stmt ;

甚至

set @qry1:= concat('select * from ', (select tableName from test limit 1));
select @qry1;
prepare stmt from @qry1 ;
execute stmt ;

SQLFiddle示例: http ://sqlfiddle.com/#!9/a787e3/1

注意:SqlFiddle不允許在右編輯器中運行execute ,因此我不得不使用視圖。

免責聲明/說明:

您應該清除tableName表的所有輸入。 這樣一來,沒人會在該表中插入SQL並執行它。

此外,請注意,在真實數據庫中,表選擇查詢將具有where條件。

例:

set @qry1:= concat('select * from ', (select tableName from test where id='something'));
  SELECT * 
   FROM first_table t1 
    WHERE EXISTS (SELECT * FROM other_table t2 WHERE t1.other_table_id = t2.id)
mysql> SELECT @other_table := other_table FROM first_table WHERE 1 = 1;
mysql> SET @s = CONCAT("SELECT * FROM ", @other_table);
mysql> PREPARE stmt FROM @s;
mysql> EXECUTE stmt;
mysql> DEALLOCATE stmt;

在這里應該將WHERE 1=1更改為僅返回結果集中的一行

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM