Emitting a subquery in the FROM in Django

Viewed 30

I am trying to produce SQL like so:

SELECT ...
FROM bigtable
INNER JOIN (
   SELECT DISTINCT key
   FROM smalltable
   WHERE smalltable.x = 'user_input'
) subq ON bigtable.key = subq.key

I have tried a handful of stuff with Django, and so far I've got:

subq = Smalltable.objects.filter(x='%s').values("key").distinct("key")
queryset = Bigtable.objects.extra(
    tables=[f"({subq.query}) subq"],
    where=["bigtable.key = smalltable.key"],
    params=["user_input"],
)

The goal here is a cross join on bigtable and the DISTINCT smalltable. The ON clause is then replaced by a condition in the WHERE. In other words, a valid old-school inner join.

And Django ALMOST has it. It is producing SQL like so:

SELECT ...
FROM bigtable, "(SELECT DISTINCT ...) subq"
WHERE (bigtable.key = subq.key)

Note the double quotes - Django expects a table literal only there and is escaping it as so. How can I get this query done, in either this way or another way? It is important for me that it's an actual join vs IN or EXISTS for query planning purposes.

0 Answers
Related