Question

i have a table of itineraries and a table of associated images with a foreign key. i'd like to get a list of itineraries with its first image, so ordering itineraries_images by sort with a limit of 1

CREATE TABLE itineraries (
  id int(10) AUTO_INCREMENT,
  is_live tinyint(1),
  title varchar(255),
  body text,
  PRIMARY KEY (id) 
)

CREATE TABLE itineraries_images (
  id int(10) AUTO_INCREMENT,
  itineraries_id int(10),
  is_live tinyint(1),
  caption varchar(255),
  image_src varchar(255),
  sort smallint(5),
  PRIMARY KEY (id),
  KEY itineraries_id (itineraries_id)
)

i'm doing a left join, but it doesn't sort the joined table

SELECT i.*, ii.image_src, ii.caption 
FROM itineraries AS i 
LEFT OUTER JOIN itineraries_images AS ii ON i.id=ii.itineraries_id AND ii.is_live=1 
WHERE i.is_live=1 
GROUP BY ii.itineraries_id  
ORDER BY i.id, ii.sort

been looking at subqueries... but still can't get it working :(

many thanks,

rob.

Was it helpful?

Solution

This will do the job and will give you the latest image_src as your definitions shows the id in images table is AUTO_INCREMENT so ORDER BY ii.id DESC in group_concat will group the images in descending order and by using SUBSTRING_INDEX will give you the latest image

SELECT i.*, 
SUBSTRING_INDEX(GROUP_CONCAT( ii.image_src ORDER BY ii.id DESC ),',',1) image_src ,
SUBSTRING_INDEX(GROUP_CONCAT( ii.caption  ORDER BY ii.id DESC ),',',1)  caption     
FROM itineraries AS i 
LEFT OUTER JOIN itineraries_images AS ii ON i.id=ii.itineraries_id AND ii.is_live=1 
WHERE i.is_live=1 
GROUP BY i.id
ORDER BY i.id, ii.sort

OTHER TIPS

Presumably you want the first image in each itinerary. This is how you do it using not exists:

SELECT i.*, ii.image_src, ii.caption 
FROM itineraries i LEFT OUTER JOIN
     itineraries_images ii
     ON i.id=ii.itineraries_id AND ii.is_live=1 
WHERE i.is_live = 1 and
      not exists (select 1
                  from itineraries_images ii2
                  where ii2.itineraries_id = ii.itinieraries_id and
                        ii2.is_live = 1 and
                        ii2.sort > ii.sort
                 )
ORDER BY i.id
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top