【问题标题】:MYSQL: subquery return as table name in joinMYSQL:子查询作为连接中的表名返回
【发布时间】:2013-08-27 07:46:17
【问题描述】:

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

动态表(动态表)

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

【问题讨论】:

  • 是的....你试过了吗..?但您忘记包含dt.product_id 作为回报
  • Mysql 不是 sql server
  • 构建动态sql语句。
  • @dipesh:是的,我试过了..它会抛出 mysql 错误未知列“p.tableid”,如果我直接输入任何值表示而不是“p.tableid”并且错误显示未知列“dt” .product_id'。
  • 子查询中的 p.tableid 会出错,因为子查询中没有 p 的别名

标签: php mysql sql join subquery


【解决方案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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-26
    • 2016-04-20
    • 1970-01-01
    • 2021-05-10
    • 2021-02-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多