I’m building a web app of classified ads (it’s my first professional PHP app). I have a table with the Ads and other with the images for each Ad. Each ad can have up to 4 images. It all worked fine while I was adding only one image per ad. Now, when I ad more than one image per ad that ad repeats in the listing (one time per each image it has). Here’s the SQL I’m using:
SELECT
sun_classified_ads.ad_id,
sun_classified_ads.insertion_datetime,
sun_classified_ads.title,
sun_classified_ads.description,
sun_classified_ads.maker,
sun_classified_ads.model,
sun_classified_ads.location,
sun_classified_ads.price,
sun_classified_ads_images.filename_mini,
sun_classified_ads_images.size_attr_mini,
sun_classified_ads_images.description AS image_description
FROM sun_classified_ads
INNER JOIN sun_classified_ads_images ON sun_classified_ads.ad_id = sun_classified_ads_images.ad_id
How can I do so it only uses the first image for that Ad from the sun_classified_ads_images table?
MySQL has a “feature” called Hidden Columns. You can get one image per ad using the following:
Just a caution. There is no guarantee that this will return the first ad. There is not guarantee that the three fields from images will actually come from the same record (though in practice they do). However, this is probably the easiest way to get what you want.
The following query does do what you want, but is a bit more work:
This assumes that
ad_image_idis a field that can be used to define the ordering of the images.