[英]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. 我有一个包含页面/广告的表格,另一个表格包含每个广告的x图片。 The pictures table also have a “sortorder” column.
图片表还有一个“sortorder”列。
I'm trying to write some SQL, where i get the title from an ad and only one picture where sortorder is the lowest. 我正在尝试编写一些SQL,我从广告中获取标题,只有一张图片,其中sortorder是最低的。
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. 也许我必须在SELECT中做一个SELECT,不知道。
You'll need a table expression (that I named m
) to compute the minimum sortorder
for each ad. 您需要一个表格表达式(我将其命名为
m
)来计算每个广告的最小sortorder
。 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.