简体   繁体   中英

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.

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

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

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