INNER JOIN WITH ORDER BY

Asked

Viewed 3,954 times

3

In MYSQL I have two tables, product and product_photo.

In the product table_photo has a field that calls first that normally its value is 0. In the administrative system of the site there can be the marking of which the photo will be the first (main) and then this field first gets the value 1.

Table Product:

inserir a descrição da imagem aqui

Table Product_photo:

inserir a descrição da imagem aqui

When listing all products on the site, only one photo of each product is presented. And I wanted it to be just the photo in that field first is equal to 1.

I’ve been using the select:

SELECT * FROM produto 
INNER JOIN produto_foto ON produto_foto.idproduto = produto.id
GROUP BY produto.id
ORDER BY produto.id DESC, primeira_foto.primeira DESC

Expected result:

chupeta - fotoX.jpg

caderno - fotoX.jpg

tesoura - foto.jpg (nesse caso não existiu marcação de qual é a foto 1, então pegaria o registro de menor ID da tabela Produto_Foto)
  • 1

    Try to illustrate your tables with data and try to add an expected result. Like the illustration of that question, it would make it a lot easier to help with an answer. http://answall.com/questions/131637/buscar-somente-o-menor-n%C3%Bamero-de-cada-letra/131640#131640

  • Thanks for the tip @Marconi, I edited here!

  • 1

    I improved it. Look how it turned out. I think that makes it better to understand @caiocafardo.

1 answer

3


Hey, buddy, try this.

SELECT p.*, pf.* 
  FROM produto p
 INNER JOIN produto_foto pf ON p.id = pf.idproduto
 INNER JOIN ( SELECT id
                FROM produto_foto 
               WHERE primeira = 1
               UNION
              SELECT MIN(id) AS id
                FROM produto_foto
               GROUP BY idproduto HAVING SUM(primeira) = 0 ) i ON pf.id = i.id

An example to run here: http://sqlfiddle.com/#! 9/96324/1

  • The Result he wants is not that @Emerson.

  • @Marconi, only if I got it wrong. It seems the field primeira is has the behavior of a boolean. @caiocafardo wants each product to return the photo with field primeira = 1, but not all products have pictures like this. When there is no photo that fits this condition returns that photo of the product that has the smallest ID. Correct me if I got it wrong.

  • That’s right @Emerson, but your query is bringing the 2 records from chupeta.

  • No you’re not, you ran the example I put in the reply text?

  • True, that’s exactly what he wants. + 1

  • That’s it ae! Thanks for the help and concern!

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.