0

Here's the raw query I feed to the ORM I'm using:

SELECT
    "fightEventId"
FROM
    ${EDBTableNames.LOCATION_TIME_SLOT} AS lts
WHERE
    "fightId" IN (
        SELECT
            f.id
        FROM
            ${EDBTableNames.FIGHTS} AS f
        WHERE
            f.status = '${EFightStatus.CONFIRMED}'
    )
    AND "fightEventId" IN (
        SELECT
            fe.id
        FROM
            ${EDBTableNames.FIGHT_EVENTS} AS fe
        WHERE
            ${status.includes(EFightEventStatus.ONGOING)}
            AND (
                NOW() at time zone 'utc' >= fe.from AND NOW() at time zone 'utc' <= fe.to
            )
            OR ${status.includes(EFightEventStatus.UPCOMING)} AND NOW() at time zone 'utc' <= fe.to
            OR ${status.includes(EFightEventStatus.FINISHED)} AND NOW() at time zone 'utc' > fe.to
        ORDER BY fe."from" ASC
    )
GROUP BY "fightEventId"
HAVING
    COUNT("fightId") > ${SHOW_WITH_NUMBER_OF_FIGHTS}
LIMIT ${limit}
OFFSET ${page * limit};

The problem with this query is that even though fight events are ordered by the "from" date: ORDER BY fe."from" ASC, this subquery order is not maintained in the whole query. I need it to be maintained.

What would be the right way to do this? By the "right way" I mean performance and clarity.

Here is a bunch of options, but I'm a little bit confused as to which one to go for.

ORDER BY the IN value list

P.S.

SHOW_WITH_NUMBER_OF_FIGHTS is an integer and as of now it's required to be equal to 4.

one_tit_shark
  • 89
  • 1
  • 6
  • What if the query over `${EDBTableNames.FIGHT_EVENTS}` returns the same fe.id multiple times with different fe."from" ? – jjanes Jun 15 '21 at 13:41
  • @jjanes As far as I understand, according to the business logic, this scenario must be impossible. – one_tit_shark Jun 15 '21 at 14:06
  • @jjanes any ideas how to do that? – one_tit_shark Jun 15 '21 at 19:44
  • I'd like to rewrite it using `unnest `, but I can't figure out how... – one_tit_shark Jun 15 '21 at 20:04
  • You would want to rewrite it to use a `JOIN...ON ( "fightEventId"=fe.id)` rather than an IN list. That will make other fields from the table available for use in a sort. You might need to aggregate it with a dummy like `max(fe."from")`. If the business logic guarantees there can only be one distinct value, then taking the max will just yield that value. – jjanes Jun 15 '21 at 20:30

0 Answers0