Skip to content
Advertisement

How to use Distinct OR Group by with Inner Join?

have a problem with sql query, simple one but though I’m sitting on it 3d day and cant figure out what is wrong, please help.

Table 1: enter image description here

Table 2

enter image description here

Result enter image description here

Desired result – in my reslt I want to display each portfolio ID ONLY ONCE.

sql query:

SELECT DISTINCT `portfolio`.`id`, `Description`,`Title`, `portfolio_images`,`Date_created`
FROM `portfolio`
    LEFT OUTER JOIN `portfolio_images` ON `portfolio_images`.`portfolio_id` = `portfolio`.`id`

Any ideas / solutions are welcomed. Thank you

Advertisement

Answer

Use row_number():

SELECT p.*, pi.*
FROM `portfolio` LEFT OUTER JOIN
     (SELECT pi.*,
             ROW_NUMBER() OVER (PARTITION BY portfolio_id ORDER BY portfolio_id) as seqnum
      FROM portfolio_images pi
     ) pi
     ON pi.portfolio_id = p.id AND seqnum = 1;

EDIT:

In older versions, if you want just one column from portfolio_images you can use a correlated subquery:

select p.*,
       (select pi.portfolio_images
        from portfolio_images pi
        where pi.portfolio_id = p.id
        limit 1
       ) as portfolio_images
from portfolio p;

As for your query, DISTINCT applies to all columns, so clearly different columns have different values, even if the columns from portfolio are the same.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement