NOTE: I WANT TO AVOID DISTINCT ON FOR PERFORMANCE REASONS.
NOTE 2: I WAS WRONG. USING PROPER INDEXES THE QUERY WORKED AWESOME THANKS TO @Gordon Linoff!
Having the following structure:
| id | image_url | sort | t1_id |
|----|---------------|------|-------|
| 1 | https://.../1 | 10 | 1 |
| 2 | https://.../2 | 20 | 1 |
| 3 | https://.../3 | 30 | 1 |
| 4 | https://.../4 | 30 | 2 |
| 5 | https://.../5 | 20 | 2 |
| 6 | https://.../6 | 10 | 2 |
I want to fetch the lowest sort row's image_url column by t1_id, similar to the following:
SELECT * FROM t2 WHERE MIN(sort) GROUP BY (t1_id);
Getting the following result:
| id | image_url | sort | t1_id |
|----|---------------|------|-------|
| 1 | https://.../1 | 10 | 1 |
| 6 | https://.../6 | 10 | 2 |
Thanks in advance!
DISTINCT ONis not slower than any other technique to achieve the same (e.g. withROW_NUMBERor a sbquery). So, your problem is more general and you may just want to provide your DBMS with an appropriate index.