Query output, is an input for another query does - not work
I want to use the return of one query as the input for another.
When I run them individually they work fine, but when I combine them in one, it does not work.
The individual queries are:-
select ja.id
from job_applications ja
join users u
on u.id = ja.user_id
where u.email='xxxxx@gmail.com'
order by ja.updat开发者_JAVA技巧ed_at desc
limit 1
The output being
308480
and when I use this value as an input for another query I get my desired result
select * from delayed_jobs dj
where handler like "%308480%"
BUT, now when I try to run it as one single query it does not work (i get no output)
select * from delayed_jobs dj
where handler like
"%(select ja.id
from job_applications ja
join users u
on u.id = ja.user_id
where u.email='xxxxx@gmail.com'
order by ja.updated_at desc
limit 1)%"
Please help.
You can't execute SQL code inside of a like statement like that. You need to generate the like expression by concatenating the result together something like this:
where handler like
concat('%', (select ja.id
from job_applications ja
join users u
on u.id = ja.user_id
where u.email='xxxxx@gmail.com'
order by ja.updated_at desc
limit 1),
'%')
For dynamic SQL you should use stored procedure, like mellamokb explained in his answer. However, your query is not really dynamic and therefore you can use a subselect. For example:
select * from delayed_jobs dj
where handler like
(select concat('%', ja.id, '%')
from job_applications ja
join users u
on u.id = ja.user_id
where u.email='xxxxx@gmail.com'
order by ja.updated_at desc
limit 1)
UPDATE
sorry, apparently i misinterpreted mellamokb's answer ... indeed it's the same as mine ...
精彩评论