简体   繁体   中英

How do I inner join 2 SQL tables, but only take the first result from the second table?

I'm building a page where u can rent apartments and stuff, and there are a lot of images of each of these apartments, so I have made 2 tables. One with all apartments, and one with all images, that i connect to a specific apartment with a foreign key. I want all the apartments, but i only want 1 image per apartment.

I have tried to do LIMIT 1, but then it limits apartments to 1 as well.

This is my code:

$sql = "SELECT bolig_boliger.id AS bolig_id, titel, areal, rooms, 
indflytning, husleje, image
FROM bolig_boliger
INNER JOIN bolig_images ON bolig_boliger.id = bolig_images.bolig_id";

One simple method sa correlated subquery. Of course, you have not shown the layout of the tables, so I have to speculate on what columns go where and how to identify the latest row. A reasonable guess is:

SELECT b.id AS bolig_id, titel, areal, rooms, indflytning, husleje, image
FROM bolig_boliger b INNER JOIN
     bolig_images i
     ON b.id = i.bolig_id
WHERE i.id = (SELECT MAX(i2.id) FROM bolig_images i2 WHERE i2.bolig_id = i.bolig_id)

Join with a subquery that returns one row per apartment ID, instead of joining with the whole table.

SELECT b.id, b.titel, b.areal, b.rooms, b.indflytning, b.husleje, i.image
FROM bolig_boliger AS b
JOIN (
    SELECT bolig_id, MAX(image) AS image
    FROM bolig_images
    GROUP BY bolig_id
) AS i ON b.id = i.bolig_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