0

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

动态表(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;
4

1 回答 1

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;
于 2013-08-27T07:57:58.547 回答