Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

php - How to join two table and get the correct records

I have one table containing pages/ad and another table with x pictures for each ad. The pictures table also have a “sortorder” column.

I’m trying to write some SQL, where i get the title from an ad and only one picture where sortorder is the lowest.

So far i’m doing this. But that just gave me a picture, but not the picture i want.

SELECT ads.id, ads.title, min(ads_gallery_files.filename) as picture, clients.name
FROM ads LEFT JOIN ads_gallery_files ON ads_gallery_files.ads_id=ads.id 
GROUP BY ads.id

I also have a client table, where i can see who created the ad. I’m using a left join to collect that name

LEFT JOIN clients ON clients.id=ads.client_id

Maybe i have to do a SELECT in a SELECT, don’t know.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You'll need a table expression (that I named m) to compute the minimum sortorder for each ad. Then you can just join this table to filter out the "extra" rows you don't want.

For example:

select
   a.id, a.title, f.filename as picture, c.name
from ads a
join ads_gallery_files f on f.ads_id = a.id
join ( -- this is called a "table expression" since it acts as a table
  select ads_id, min(sortorder) as minorder
  from ads_gallery_files f
  group by ads_id
) m on m.ads_id = f.ads_id and m.minorder = f.sortorder
left join clients c on c.id = a.client_id

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...