I wrote a query to select products from MySQL:
Here's what it looks like:
SELECT `products`.`id` AS `id`, `products`.`name` AS `name`, `products`.`slug` AS `slug`, `products`.`ord` AS `ord`,
SUBSTRING_INDEX(GROUP_CONCAT(products_photos.name ORDER BY products_photos.ord ASC SEPARATOR ","), ",", 1) AS `photo`,
SUBSTRING_INDEX(GROUP_CONCAT(products_attributes.price ORDER BY products_attributes.price ASC SEPARATOR ","), ",", 1) AS `price`
FROM `products`
LEFT JOIN `products_photos` ON `products`.`id` = `products_photos`.`product_id`
LEFT JOIN `products_attributes` ON `products`.`id` = `products_attributes`.`product_id`
LEFT JOIN `products_categories` ON `products`.`id` = `products_categories`.`product_id`
WHERE `products_categories`.`category_id` = '5' AND `products`.`status` = '1'
GROUP BY `products`.`id`
ORDER BY `ord` ASC
I'm wondering about photos and attributes part of query, is there a better way to select first photo and smallest price from joined tables? There will be a lot of products in my table and I'm worried about future performance as I'm not very good at MySQL :)
Any pointers would be appreciated :)
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
SELECT
`products`.`id` AS `id`,
`products`.`name` AS `name`,
`products`.`slug` AS `slug`,
`products`.`ord` AS `ord`,
SUBSTRING_INDEX(GROUP_CONCAT(products_photos.name
ORDER BY
products_photos.ord ASC SEPARATOR ','),
",",
1) AS `photo`,
SUBSTRING_INDEX(GROUP_CONCAT(products_attributes.price
ORDER BY
products_attributes.price ASC SEPARATOR ','),
",",
1) AS `price`
FROM
`products`
LEFT JOIN
`products_photos`
ON `products`.`id` = `products_photos`.`product_id`
LEFT JOIN
`products_attributes`
ON `products`.`id` = `products_attributes`.`product_id`
INNER JOIN
`products_categories`
ON `products`.`id` = `products_categories`.`product_id`
WHERE
`products_categories`.`category_id` = '5'
AND `products`.`status` = '1'
GROUP BY
`products`.`id`
ORDER BY
`products`.`ord` ASC