![](/img/trans.png)
[英]How do I inner join 2 SQL tables, but only take the first result from the second table?
[英]Return the first index from second table in INNER JOIN SQL
我有以下表,並想編寫一個 SQL 查詢以從與內部聯接匹配的第二個表中返回第一個結果。
Cars
id brand model
1 Ford Mustang
2 Audi A4
3 BMW 3
Images
id img_url car_id
1 https://example.s3.amazonaws.com/ford_1.jpg 1
2 https://example.s3.amazonaws.com/ford_2.jpg 1
3 https://example.s3.amazonaws.com/audi_1.jpg 2
4 https://example.s3.amazonaws.com/audi_2.jpg 2
5 https://example.s3.amazonaws.com/audi_3.jpg 2
6 https://example.s3.amazonaws.com/bmw_1.jpg 3
7 https://example.s3.amazonaws.com/bmw_2.jpg 3
我正在對cars.id = images.car_id 進行INNER JOIN,但似乎無法找到將圖像表中的結果限制為將cars.id 與images.car_id 匹配的第一行的方法。
理想情況下,我希望返回此內容:
id brand model img_url
1 Ford Mustang https://example.s3.amazonaws.com/ford_1.jpg
2 Audi A4 https://example.s3.amazonaws.com/audi_1.jpg
3 BMW 3 https://example.s3.amazonaws.com/bmw_1.jpg
非常感謝任何幫助,干杯!
一種方法使用row_number()
select i.*
from cars c join
(select i.*,
row_number() over (partition by car_id order by id) as seqnum
from images i
) i
on i.car_id = c.id
where seqnum = 1;
另一種方法將所有過濾移至where
子句:
select i.*
from images i
where exists (select 1
from cars c
where i.car_id = c.id
) and
i.id = (select min(i2.id)
from images i2
where i2.car_id = i.car_id
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.