On Aug 27, 2009, at 7:55 PM, Mike Conley wrote:

> Here is the problem
>
> I have two mapped classes (A and B) and want to create a union_all  
> query.
>
> q1 = session.query(A.data, '\'A\'')  # includes a literal 'A' in the  
> result
> q2 = session.query(B.data, '\'B\'')
> qry = q1.union_all(q2)
>
> generates this SQL:
> SELECT anon_1.data, 'A'
> FROM (SELECT a.data AS data, 'A'
> FROM a UNION ALL SELECT b.data AS data, 'B'
> FROM b) AS anon_1
>
> and plugs a 'A' into each row of the result
>
> I would want to get 'A' or 'B' in the result depending on which  
> query produced the row and it would seem to work if I could apply a  
> label to the literal column 'A' similar to what I can do to the  
> columns. Get the effect of
>
> q1 = session.query(A.data.label('somestuff'), '\'A 
> \''.label('somelabel'))
>     # of course str objects do not have a method label, so that  
> doesn't work
> q2 = session.query(B.data, '\'B\'')
> qry = q1.union_all(q2)
>
> and generate SQL like
> SELECT anon_1.somestuff AS somestuff, anon_1.somelabel as somelabel
> FROM (SELECT a.data AS somestuff, 'A' as somelabel
> FROM a UNION ALL SELECT b.data AS data, 'B'
> FROM b) AS anon_1
>
> which will give the desired result

you can say....literal("A").label('somelabel') to get the column in  
there.   or literal_column() which will skip creating a bind param.


--~--~---------~--~----~------------~-------~--~----~
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