MariaDB,如何使用字段名作为表名?

时间:2017-05-24 05:48:00

标签: mysql sql mariadb

我正在尝试创建一个表,该表可以引用另一个表,其中引用的表在其中一个记录中配置:

规则表'tblRules':

calc_insol['new'] = pd.to_datetime(calc_insol.iloc[:,0])
meas_insol['new'] = pd.to_datetime(meas_insol.iloc[:,1])
df = pd.merge(calc_insol, meas_insol, on='new')
#if necessary
df = df.drop('new',axis=1)

测试表'tblTest':

    biRuleID, BIGINT, Unsigned, Primary Key
    biTableID, BIGINT, Unsigned, Link to record in 'other' table
    vcDescription, VARCHAR[64], Description of rule
    vcTableName, VARCHAR[64], The name of the table containing the rule details.

要测试,tblRules包含一条记录:

    biTestID, BIGINT, Unsigned, Primary Key
    vcTest, VARCHAR[64], A test string

并且tblTest包含:

    1, 1, Testing rule, tblTest

现在我想提取数据:

    1, Hello World

然而,当我尝试执行查询时,它似乎将t1.vcTableName作为表的名称而不是vcTableName包含的内容,是否有办法对此进行排序?

1 个答案:

答案 0 :(得分:0)

你可以使用动态的sql来实现它,虽然我认为你必须使用你的数据库设计做事,因为它不太有效

set @qry = (
    SELECT
      concat('SELECT * FROM tblRules t1 LEFT JOIN ', t1.vcTableName, ' t2 ON t1.biTableID = t2.biTestID WHERE t1.biRuleID=1') 
    FROM 
      tblRules t1 
    WHERE 
      t1.biRuleID=1
);
PREPARE qry FROM @qry;
EXECUTE qry;
DEALLOCATE PREPARE qry;