Question

I'm making a search function for a webshop and to display the results I'm trying to create a SQL query on multiple tables. This query is working:

SELECT ps_product_lang.id_product , ps_product_lang.name as product_name ,
ps_product_lang.description_short,
ps_product_lang.link_rewrite as product_link_rewrite , 
ps_product_lang.meta_title , ps_product.reference , 
ps_product.id_category_default , ps_product.on_sale , ps_product.price , 
ps_category_lang.name as category_name , 
ps_category_lang.link_rewrite as category_link_rewrite , ps_image.id_image
FROM ps_product_lang
INNER JOIN ps_product
INNER JOIN ps_category_lang
ON ps_product.id_category_default=ps_category_lang.id_category
INNER JOIN ps_image
ON ps_product_lang.id_product=ps_image.id_product
WHERE ps_product_lang.name LIKE '%simone%' OR
ps_product.reference LIKE '%simone%' ORDER BY ps_product_lang.id_product ASC

In the search results I want to display only one image. But with this query above I get all the id_images by the desired id_product. I tried different ways to limit it like:

ON ps_product_lang.id_product=ps_image.id_product = (SELECT id_image FROM ps_image LIMIT 1)

But whatever I try, I get no results anymore or I have an error in my syntax. Who can give me a push in the right direction?

Was it helpful?

Solution 2

I was too much focused on the id_image. What I want is to view an individual product only 1 time. So a simple group by does the job.

SELECT ps_product_lang.id_product , ps_product_lang.name as product_name , ps_product_lang.description_short , ps_product_lang.link_rewrite as product_link_rewrite , ps_product_lang.meta_title , ps_product.reference , ps_product.id_category_default , ps_product.on_sale , ps_product.price , ps_category_lang.name as category_name , ps_category_lang.link_rewrite as category_link_rewrite , ps_image.id_image
FROM ps_product_lang
INNER JOIN ps_product
INNER JOIN ps_category_lang
ON ps_product.id_category_default=ps_category_lang.id_category
INNER JOIN ps_image
ON ps_product_lang.id_product=ps_image.id_product
WHERE ps_product_lang.name LIKE '%simon%' OR ps_product.reference LIKE '%simon%' GROUP BY ps_product_lang.id_product ORDER BY ps_product_lang.id_product ASC

OTHER TIPS

If you just want one image per product, use a simple sub select to get one image id, the maximum image id for instance. That means: Remove the join of ps_image completely.

SELECT 
  ps_product_lang.id_product , ...
  ps_category_lang.link_rewrite as category_link_rewrite , 
  (
    select max(id_image) 
    from ps_image 
    where id_product = ps_product_lang.id_product
  ) as id_img
FROM ps_product_lang
...
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top