Search only data from two tables with different id’s

Asked

Viewed 36 times

1

Good,

I have 2 tables:

Cars:

  • id;
  • model;
  • Comb;
  • price;

Carros_img:

  • id;
  • id_fk; (Foreign key of Cars)
  • img;

I do this research:

SELECT DISTINCT carros.id, carros.modelo, carros_img.img, carros_desc.comb, carros_desc.preco 
	from carros, carros_desc, carros_img 
	where carros.id = carros_desc.id_fk 
	AND carros.id = carros_img.id_fk 
	order by carros.id ASC

And appears:

inserir a descrição da imagem aqui

In id (table id cars) appears some equal id’s as I do to only appear 1 of each type:

inserir a descrição da imagem aqui

2 answers

3


I think GROUP BY resolves (I have not tested)

SELECT DISTINCT carros.id, carros.modelo, carros_img.img, carros_desc.comb, carros_desc.preco 
from carros, carros_desc, carros_img 
where carros.id = carros_desc.id_fk 
AND carros.id = carros_img.id_fk 
GROUP BY carros.id 
order by carros.id ASC

1

In the Carros_img table you should have several lines for the same id but with the different img field.

Your query is correct but to appear only 1 row of each type, you have to make sure that the img column is not in select or you have to show a type of img.

Example:

SELECT DISTINCT carros.id, carros.modelo, carros_img.img, carros_desc.comb, carros_desc.preco 
    from carros, carros_desc, carros_img 
    where carros.id = carros_desc.id_fk 
    AND carros.id = carros_img.id_fk    
        AND carros_img.img = 'smart2.jpg' -- só smart2 
order by carros.id ASC

Browser other questions tagged

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