0

Is it possible to use subquery return as a table name in join?

Dynamic Table(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      |
+--------+--------------+----------+-----------+--------+

Product Table(products)

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

xxxxxx

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

i.e(for example):

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;
5
  • Yes....have you tried it..? but you forget to include dt.product_id in return Commented Aug 27, 2013 at 7:48
  • 1
    Mysql is not sql server Commented Aug 27, 2013 at 7:51
  • build dynamic sql statements. Commented Aug 27, 2013 at 7:51
  • @dipesh: Yes i tried .. it throws mysql error unknown column 'p.tableid' and if i put any directly value means instead of 'p.tableid' & the error shows unknown column 'dt.product_id'. Commented Aug 27, 2013 at 7:55
  • in the subquery p.tableid will through error as because there is no alias for p inside subquery Commented Aug 28, 2013 at 4:00

1 Answer 1

1

You need to use LEFT JOIN into subquery.

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;
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.