Limit Result of Inner Join

0

I have a problem a few days ago. I have a select that does some inners and should return 3 lines, but one of the inners has several results linked to the result searched; how to limit to this inner get only the first result and select continue to return the 3 lines?

    SELECT 'imovel'.'imvValorImovel', 'imovel'.'imvCodigo', 
          'imovel'.'broCodigo', 'imovel'.'imvDormitorio', 'imovel'.'imvSuite', 
          'imovel'.'tpoCodigo', 'imovel'.'imvGaragem', 'bairro'.'broNome', 
          'tipo'.'tpoNome', 'imagem_imovel'.'imaNome' 
    FROM  'imovel' 
    INNER JOIN  'bairro' ON  'imovel'.'broCodigo' =  'bairro'.'broCodigo' 
    INNER JOIN  'tipo' ON  'imovel'.'tpoCodigo' =  'tipo'.'tpoCodigo'
    INNER JOIN  'bairro' ON  'imovel'.'broCodigo' =  'bairro'.'broCodigo'
    INNER JOIN  'imagem_imovel' ON  'imovel'.'imvCodigo' =  'imagem_imovel'.'imvCodigo 
    WHERE  'imovel'.'broCodigo' = "'.$resultado->broCodigo.'" 
    AND 'imovel'.'tpoCodigo' = "'.$resultado->tpoCodigo.'" 
    AND 'imovel'.'imvFinalidade' = "'.$resultado->imvFinalidade.'"
    LIMIT 3
    
asked by anonymous 08.08.2017 / 15:25

2 answers

2

To filter repeated results in a join you can use group by . For example, let's suppose that the table that has duplicate records for the same property is imagem_imovel :

Inthiscase,thereisonlytheproperty"1" with two images: img1 and img2. To retrieve the largest image, you will need to create a subquery in your join:

select * from imovel join bairro using (broCodigo) join tipo using (tpoCodigo) join (select max(imvNome), imvCodigo from imagem_imovel group by imvCodigo) maioresImagens using (imvCodigo);

Notice that instead of joining the table imagem_imovel a join was done with a query that returns the largest names in that table (max (imvName)) for each property (group by imvCode). The rest of the query remains and now the result will be:

The important thing here is to know how to use subqueries whenever you have a limitation on the results of a join.

    
08.08.2017 / 16:18
0

In this case, I think it would only fit one sub-select:

SELECT 
  'imovel'.'imvValorImovel', 
  'imovel'.'imvCodigo', 
  'imovel'.'broCodigo', 
  'imovel'.'imvDormitorio', 
  'imovel'.'imvSuite', 
  'imovel'.'tpoCodigo', 
  'imovel'.'imvGaragem', 
  'bairro'.'broNome', 
  'tipo'.'tpoNome',
   (SELECT  
     'imagem_imovel'.'imaNome'
    FROM 'imagem_imovel' 
    WHERE 'imagem_imovel'.'imvCodigo' = 'imovel'.'imvCodigo' 
    ORDER BY 'imagem_imovel'.'imvCodigo'  
    LIMIT 1) as 'imaNome'
FROM  'imovel' 
INNER JOIN  'bairro' ON  'imovel'.'broCodigo' =  'bairro'.'broCodigo' 
INNER JOIN  'tipo' ON  'imovel'.'tpoCodigo' =  'tipo'.'tpoCodigo'
INNER JOIN  'bairro' ON  'imovel'.'broCodigo' =  'bairro'.'broCodigo'
WHERE  'imovel'.'broCodigo' = "'.$resultado->broCodigo.'" 
AND 'imovel'.'tpoCodigo' = "'.$resultado->tpoCodigo.'" 
AND 'imovel'.'imvFinalidade' = "'.$resultado->imvFinalidade.'"
LIMIT 3
    
08.08.2017 / 21:40