如何从表表中检索表记录?

时间:2018-12-09 05:08:17

标签: mysql subquery mysql-workbench

我想从表中检索表记录,以下是我清楚解释的内容,希望您理解

这是我尝试过的方法,但未获得预期的结果。

表1

----------------------------------------------------------------------------
tables        |    id
----------------------------------------------------------------------------
test               1
pure               2
root               3
link               4
---------------------------------------------------------------------------- 

测试表

----------------------------------------------------------------------------
id    |    name    |    gender
----------------------------------------------------------------------------
1          jack           m
2          dude           m
3          crop           m
4          pert           m
----------------------------------------------------------------------------

我使用表检索测试表的查询

select * from(select tables from table1 where id=1) as info;

结果

----------------------------------------------------------------------------
tables
----------------------------------------------------------------------------
test


----------------------------------------------------------------------------

预期产量

----------------------------------------------------------------------------
id    |    name    |    gender
----------------------------------------------------------------------------
1          jack           m
2          dude           m
3          crop           m
4          pert           m
----------------------------------------------------------------------------

3 个答案:

答案 0 :(得分:0)

SELECT is, name, gender FROM test
    JOIN table1 
    ON test.id = table1.id // MATCH HERE PRIMARY KEY AND FOREIGN KEY
    ORDER BY name;// YOU CAN ALSO ODER BY YOUR TEST.ID

答案 1 :(得分:0)

您可以使用openquery解决它。创建一个存储过程,以运行查询,如下所示:

delimiter //;
create or replace procedure execute_dynamic_sql(tableName  in  varchar(100))
begin
    set @query = 'select * from ?'; 
    set @tableName = tableName; 
    prepare stmt1 from @query;
    execute stmt1 using @tableName;
    deallocate prepare stmt1;

end ;
//

通过任何表名参数调用存储过程:

call execute_dynamic_sql('your_table_name') ;

答案 2 :(得分:0)

您不会使用子查询从另一个表中获取数据。您必须为此使用prepare语句。

SET @table = (select tables from table1 where id=1);
set @qry = concat('select * from ',@table);
prepare stmt from @qry;
execute stmt;