What is correct way to join two subqueries? The example is somewhat
contrived, but illustrates the problem.

SQL might look like this

SELECT x.blah, y.blah
FROM (SELECT id, data AS blah FROM a) AS x
JOIN (SELECT id, data AS blah FROM b) AS y
  ON x.id = y.id

Mapped classes are:

class A(Base):
    __tablename__ = 'a'
    id = Column(Integer, primary_key=True)
    data = Column(String)
    def __repr__(s):
        return '<A id:%s data:%s>' % (s.id, s.data)

class B(Base):
    __tablename__ = 'b'
    id = Column(Integer, primary_key=True)
    data = Column(String)
    def __repr__(s):
        return '<B id:%s data:%s>' % (s.id, s.data)

with some data:

session.add_all([A(data='a1'),A(data='a2'),B(data='b1'),B(data='b2'),])
session.commit()

and subqueries:

subqa = session.query(A.id, A.data.label('blah')).subquery()
subqb = session.query(B.id, B.data.label('blah')).subquery()

First attempt:

session.query(subqa.c.blah, subqb.c.blah)

as expected this give a cross join of all A's and B's

Second attempt:

session.query(subqa.c.blah, subqb.c.blah).join((subqb,subqb.c.id==subqa.c.id
))

gives and error:
AttributeError: 'NoneType' object has no attribute 'base_mapper'

probably because subqa is not a mapped entity

Third attempt (this one works):

class SubA(object): pass
mapper(SubA,subqa)
compile_mappers()
s.query(SubA.blah, subqb.c.blah).join((subqb,subqb.c.id==SubA.id))

Is there a more direct way without needing to create the temporary mapped
entity?

It appears that when using Session.query.join(), the first parameter to
query() must be a mapped entity or an attribute of a mapped entity. Is that
true?



-- 
Mike Conley

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to sqlalchemy@googlegroups.com
To unsubscribe from this group, send email to 
sqlalchemy+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to