John K
John K

Reputation: 353

Joining two tables with multiple field sorting in MySQL

I have two tables and I have to join it. table structures are

tblproducts --> id(int,pk), name(varchar)

tblphotos ---> id(int,pk), productid(int,fk), photo(varchar), display_order(int)

There can be more than one photos for each product, I need to get one photo with lowest display_order.

I need, tblproducts.id, tblproducts.name, tblphotos.photo(photo with least display_order) also I need to get the whole list as tblproducts.id in ascending order.

Upvotes: 1

Views: 172

Answers (2)

Soner Gönül
Soner Gönül

Reputation: 98740

Select tblproducts.id, tblproducts.name, (Select Top 1 tblphotos.photo FROM tblphotos, tblproducts Where tblphotos.productid = tblproducts.id Order By display_order)
From tblproducts, tblphotos
Where tblproducts.id = tblphotos.productid
Order by  tblproducts.id

EDIT: Oppss! I didn't see tag. This is for MSSQL by the way.

Yes this query looks like repeating. I should delete Where clause.

Select tblproducts.id, tblproducts.name, (Select Top 1 tblphotos.photo FROM tblphotos, tblproducts Where tblphotos.productid = tblproducts.id Order By display_order)
From tblproducts
Order by  tblproducts.id

Upvotes: 1

danishgoel
danishgoel

Reputation: 3645

I haven't tested the following query but it should work, give it a try:

SELECT 
    p.id, p.name, f.photo 
FROM
    tblproducts p,
    (
        SELECT productid, MIN(display_order) AS min_display_order 
        FROM tblphoto 
        GROUP BY productid
    ) AS t,
    tblphoto f 
WHERE 
    p.id = t.productid AND 
    t.productid = f.productid AND 
    t.min_display_order = f.display_order 
ORDER BY p.id

Upvotes: 0

Related Questions