MYSQL:子查询在连接中作为表名返回

时间:2013-08-27 07:46:18

标签: php mysql sql join subquery

是否可以在连接中使用子查询返回作为表名?

动态表格(动态表格)

+--------+--------------+----------+-----------+--------+
| 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;

1 个答案:

答案 0 :(得分: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;