Join one to many and retrieve single result

前端 未结 3 778
北恋
北恋 2021-02-13 03:09

I have two tables, in PostgreSQL if that matters, with one to many relations. I need to join them so that for each \"one\" I only get single result from the \"many\" table. Not

3条回答
  •  北海茫月
    2021-02-13 03:41

    PostgreSQL supports window function. Try this,

    SELECT d.ID, d.NAME, d.DATE, d.CODE1, d.CODE2
    FROM
    (
      SELECT  a.ID, a.NAME, a.DATE,
              b.CODE1, b.CODE2,
              ROW_NUMBER() OVER(PARTITION BY a.ID ORDER BY b.SORT ASC, b.CODE2 DESC) AS ROWNUM
      FROM    TableA a
              INNER JOIN TableB b
                ON a.ID = b.ID
    ) d
    WHERE d.RowNum = 1
    

    SQLFiddle Demo

提交回复
热议问题