在连接中选择最小值的更好方法是什么?

时间:2017-07-06 12:09:22

标签: mysql join query-performance

我想要根据联合表中的日期选择最旧的媒体。查询工作正常,但我想知道它是否是正确的性能解决方案,或者有更好的方法来执行此操作。

SELECT product.`product_id`, product.`title`, product.`price`, 
media_gallery.`thumbnail`, product.`special_price` 
FROM product 
LEFT JOIN 
(SELECT product_media.`product_id`, product_media.`media_id` 
FROM product_media ORDER BY product_media.`added_on` ASC LIMIT 1) product_media 
ON product.`product_id` = product_media.`product_id` 
LEFT JOIN media_gallery ON product_media.`media_id` = media_gallery.`media_id` 
GROUP BY product.`product_id` 
LIMIT 10

我有三张桌子,我想从中选择单张图片的产品,图片应该是最早的。图像存储在media_gallery中,图像在product_media中分配。该产品可以有多个图像,这些图像在product_media中引用。我想选择product_id,product.title,product.price,product.special_price,media_gallery.thumbnail。缩略图应该是最早添加的图像

CREATE TABLE `product_media` (
  `id` varchar(60) NOT NULL,
  `product_id` varchar(50) NOT NULL,
  `media_id` varchar(50) NOT NULL,
  `added_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `product_id_2` (`product_id`,`media_id`),
  KEY `product_id` (`product_id`),
  KEY `media_id` (`media_id`),
  CONSTRAINT `product_media_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `product` (`product_id`) ON DELETE CASCADE ON UPDATE NO ACTION,
  CONSTRAINT `product_media_ibfk_2` FOREIGN KEY (`media_id`) REFERENCES `media_gallery` (`media_id`) ON DELETE CASCADE ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8


CREATE TABLE `media_gallery` (
  `media_id` varchar(50) NOT NULL,
  `media_type` varchar(10) NOT NULL,
  `media_title` varchar(100) DEFAULT NULL,
  `media_url` varchar(255) NOT NULL,
  `thumbnail` varchar(255) NOT NULL,
  `added_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`media_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8


CREATE TABLE `product` (
  `product_id` varchar(50) NOT NULL,
 `title` varchar(255) NOT NULL,
  `description` varchar(2000) DEFAULT NULL,
  `price` decimal(10,2) NOT NULL,
  `special_price` decimal(10,2) DEFAULT NULL,
  `status` varchar(15) DEFAULT 'AVAILABLE',
  `weight` double DEFAULT NULL,
 `unit_id` varchar(50) DEFAULT NULL,
  `added_on` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`product_id`),
  UNIQUE KEY `sku` (`sku`),
  KEY `unit_id` (`unit_id`),
  CONSTRAINT `product_ibfk_1` FOREIGN KEY (`unit_id`) REFERENCES `units` (`unit_id`) ON DELETE SET NULL ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=utf8

0 个答案:

没有答案