Search code examples
sqlpostgresqlgroup-byaggregateinner-join

Inner Join with similar IDs


I have two tables, say:

Table 1

id, name, place
1, a, b
2, c, d
3, e, f

Table 2

id,text
1, hello
1, bye
1, what
2, tired

Desired Output

id, name, place, text
1, a, b, hello or bye or what (any one of the three)
2, c, d, tired

I have seen a lot of posts but I couldn't find anything similar. I am new to SQL/Postgresql. I am doing it in PostgreSQL.


Solution

  • You could use DISTINCT ON here and arbitrarily just take the alphabetically lowest text from the second table:

    SELECT DISTINCT ON (t1.id) t1.id, t1.name, t1.place, t2.text
    FROM Table1 t1
    INNER JOIN Table2 t2
        ON t1.id = t2.id
    ORDER BY
        t1.id,
        t2.text;
    

    screen capture from demo below

    Demo