简体   繁体   中英

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: 在此处输入图片说明

Table 2

在此处输入图片说明

Result在此处输入图片说明

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM