简体   繁体   English

MySQL左连接与右表具有顺序和限制

[英]MySQL left join with right table having order and limit

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 我想获取带有其第一张图片的行程列表,因此按排序方式以1个限制排序itineraries_images

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. 抢。

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 这将完成工作并为您提供最新的image_src,因为您的定义显示图像表中的id为AUTO_INCREMENT因此ORDER BY ii.id DESC中的ORDER BY ii.id DESC对图像进行分组,并使用SUBSTRING_INDEX将为您提供最新图像

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

Presumably you want the first image in each itinerary. 大概您想要每个行程中的第一张图片。 This is how you do it using not exists : 这是使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM