I would like to create a query with a nested SELECT using sqlalchemy, but I cannot get the expected result.
Of course, I simplified the following query, so it will be easy to understand for this post.
Here is the query I would like to build:
SELECT pear_table.size,
(SELECT MIN(apple.apple_date)
FROM apple
WHERE apple_id = pear_table.pear_id ) apple_min,
(SELECT max(lemon.lemon_date)
FROM lemon
WHERE lemon_id = pear_table.pear_id ) lemon_max
FROM
(SELECT pear_id
FROM pear
WHERE pear_color = 'green') pear_table
Note that I use 'pear_id' in both of my subqueries. This query works well when used as a string.
Now I'm trying to build it using sqlalchemy:
APPLE = wrapper.getMapper('apple')
LEMON = wrapper.getMapper('lemon')
PEAR = wrapper.getMapper('pear')
pear_table = select([PEAR.apple_id])
pear_table.append_whereclause(PEAR.pear_color == 'green')
apple_min = select([func.min(APPLE.apple_date).label('apple_min')])
apple_min.append_whereclause(APPLE.apple_id == pear_table.pear_id)
lemon_max = select([func.min(LEMON.apple_date).label('lemon_max')])
lemon_max.append_whereclause(LEMON.lemon_id == pear_table.pear_id)
main_query = select([pear_table.c.pear_id,
apple_min.c.apple_min,
lemon_max.c.lemon_max])
And here is what sqlalchemy will build with this code:
SELECT pear_table.size,
apple_min,
lemon_max
FROM
(SELECT pear_id
FROM pear
WHERE pear_color = 'green') pear_table,
(SELECT MIN(apple.apple_date)
FROM apple
WHERE apple_id = pear_table.pear_id ) apple_min,
(SELECT max(lemon.lemon_date)
FROM lemon
WHERE lemon_id = pear_table.pear_id ) lemon_max
The problem is that 'pear_id' is not available for my 2 subqueries 'apple' and 'lemon' because sqlalchemy puts the subqueries in the FROM clause.
I tried to fix my problem using the correlation option:
.
apple_min = select([func.min(APPLE.apple_date).label('apple_min')]).correlate(None)
.
lemon_max = select([func.min(LEMON.apple_date).label('lemon_max')]).correlate(None)
.
Here is what I get:
SELECT pear_table.size,
apple_min,
lemon_max
FROM
(SELECT pear_id
FROM pear
WHERE pear_color = 'green') pear_table,
(SELECT MIN(apple.apple_date)
FROM apple,
(SELECT pear_id
FROM pear
WHERE pear_color = 'green')
WHERE apple_id = pear_table.pear_id ) apple_min,
(SELECT max(lemon.lemon_date)
FROM lemon,
(SELECT pear_id
FROM pear
WHERE pear_color = 'green')
WHERE lemon_id = pear_table.pear_id ) lemon_max
'FROM pear_id...', .
- - ?
- ?
- sqlalchemy , ?
- SELECT?
sqlalchemy 0.4, 0,8, .