0

Lets say I have two tables:

  • ticket with columns [id,date, userid] userid is a foreign key that references user.id
  • user with columns [id,name]

And I wish to perform the following query through sqlalchemy:

select ticket.id, user.name 
from
 (
   select * from ticket
   where ticket.date >= '2015-05-18'
 ) as ticket 
left join user on ticket.user_id=user.id

I am not quite sure how to perform inner queries through sqlalchemy. Any thoughts?

Fizi
  • 1,749
  • 4
  • 29
  • 55
  • You can provide a `query` as the target for another `query`'s `.join` methods, as shown here: < http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#using-subqueries >. So first build the interior query, stored as a variable, then utilize it within a join. Alternatively, you can move the `where` clause outside, thereby removing the need for a subquery at all: `select t.id, u.name from ticket t left join user u on t.user_id = u.id where t.date >= '2015-05-18'` – ely May 19 '15 at 19:21
  • If you really wanted you could put that whole thing in text to query. so something like `results=session.execute(text())` – mstbaum May 19 '15 at 19:26

0 Answers0