2013-08-27 107 views
0

是否有可能在连接中使用子查询返回作为表名称?MYSQL:子查询返回作为连接中的表名称

动态表(dynamictable)

+--------+--------------+----------+-----------+--------+ 
| tableid| tablename | settings | pack_type | status | 
+--------+--------------+----------+-----------+--------+ 
|  24 | xxxxxx  | NULL  | F   | A  | 
|  25 | YYYYYY  | NULL  | M   | A  | 
|  30 | ZZZZZZ  | NULL  | M   | A  | 
|  26 | AAAAAA  | NULL  | M   | A  | 
+--------+--------------+----------+-----------+--------+ 

表产品(产品)

+--------------+------------+ 
| tableid  | product_id | 
+--------------+------------+ 
|   30 |   1 | 
|   30 |   2 | 
|   25 |   3 | 
|   30 |   4 | 
+--------------+------------+ 

XXXXXX

+------------+--------------+ 
| product_id | product_cost | 
+------------+--------------+ 
|   1 |   350 | 
|   2 |   200 | 
|   4 |   200 | 
+------------+--------------+ 

即(例如):

select * 
    from products as p 
    left join (select tablename 
       from dynamictable as d 
       where d.tableid = p.tableid) as dt 
    on dt.product_id = p.product_id; 
+0

是的....你有没有试过..?但你忘记包含'dt.product_id'作为回报 –

+1

Mysql不是sql server – podiluska

+0

构建动态sql语句。 –

回答

1

你需要使用LEFT JOIN进入子查询。

select * 
    from products as p 
    left join (select tablename,products.tableid 
       from dynamictable as d 
       left join products on d.tableid = products.tableid 
      ) as dt 
    on dt.product_id = p.product_id;