-1

Some SELECT statements stores in table as a field. I need to write SELECT statement that joins with some SELECT that returns SELECT. For example:

SELECT *
 FROM table1
  JOIN (SELECT t_select FROM table2 WHERE = 'some_condition')

Last SELECT SELECT t_select FROM table2 returns some SELECT statement as text. I need to join table1 with the result of the query that stores in t_select

Andrew
  • 391
  • 2
  • 4
  • 12
  • where's the schema of table1 and table2? – SMA Dec 28 '14 at 15:59
  • 1
    _good for you, go for it!_ – potashin Dec 28 '14 at 16:02
  • Question was previously asked [here](http://stackoverflow.com/questions/999200/is-it-possible-to-execute-a-string-in-mysql), though IMHO the accepted answer is to a different question, so closing as a duplicate may be inappropriate. – Kevin Dec 28 '14 at 16:11

3 Answers3

1

Do I understand? Basically, you want to "evaluate" the SELECT that is stored in the table? That seems like a really poor design to me.

If you really need to do this, you'll need to pull the SELECT statement out yourself, and send it as a second query. You can't do this in pure MySQL.

Daniel
  • 4,481
  • 14
  • 34
  • It's not poor design. The db is really huge and I store some information for fields in taht select statement – Andrew Dec 28 '14 at 16:02
  • 1
    So instead of having multiple columns, you have a raw SELECT statement that has columns it it? That pretty much defeats MySQL's query engine out of hand. What is "really huge" to you? This sounds like a design built from misunderstanding SQL and relational databases. – Daniel Dec 28 '14 at 16:05
  • Maybe OP wants a prepared statement? Can those be tabled? – Kevin Dec 28 '14 at 16:12
  • @Kevin Not in a join, no. – Daniel Dec 28 '14 at 16:18
  • It is poor design. you are basically purposefully doing sql injection ;-) – Chris Travers Oct 22 '15 at 11:50
0

Do you just want a subquery?

SELECT *
FROM table1 t1 JOIN
     (SELECT t2.* FROM table2 t2 WHERE = 'some_condition') t2
     on t1.<somecol> = t2.<someothercol>;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

All in all you can't execute the query that is stored in the table withing another query. You will have to retrieve the query first, prepare it, and then execute it. Have a look at execute immediate :

http://dev.mysql.com/worklog/task/?id=2793

http://www.postgresql.org/docs/9.1/static/ecpg-sql-execute-immediate.html

Storing sql statements in a table is not very common, and there's usually better ways to do it.

Lennart - Slava Ukraini
  • 6,936
  • 1
  • 20
  • 32