0
votes

Facts:

  • I'm writing a sqlalchemy query that uses a subquery.
  • The query is trying to pull out some user information and the subquery provides counts from some other tables that I'm trying to join back to the outer table.
  • The results I'm expecting are a user's name with a count from the payment table.

My problem is, the first FROM clause has a reference to "payment" which was present in the inner query when there is no reason for it to get included in the emitted SQL.

Why would SQL alchemy pull a reference from the inner table into the outer one?

Emitted SQL

SELECT users.name , anon_1.count  
FROM payment, users 
LEFT OUTER JOIN (
  SELECT count(payment.creator_id) AS count, payment.creator_id AS creator_id 
  FROM payment 
  INNER JOIN accounts ON accounts.id = payment.account_id 
  INNER JOIN companies ON companies.id = accounts.company_id 
  WHERE payment.approver_id IS NOT NULL 
  GROUP BY creator_id
) AS anon_1 
ON users.id = anon_1.creator_id 

Python

subquery = self.db.query(*[func.count(Payment.creator_id).label('count'),     
Payment.creator_id.label('creator_id')]). \
        join(Account, Account.id == Payment.account_id). \
        join(Company, Company.id == Account.company_id). \
        filter(Payment.approver_id != None). \
        group_by('creator_id'). \
        subquery()

query = self.db.query(*[func.concat(User.last_name, User.first_name), sub.c.count]). \
        outerjoin(subquery, User.id == sub.c.creator_id)

Edit 1

I found that I can remove the two joins and the filter from the subquery and the problem is still there.

1

1 Answers

0
votes

I found the answer. Somewhere later in the code a filter was added onto the query.