How to do SELECT on more than one database table?

2

I have two tables in the database: zip and users. Can I make a single query to get fields from the two tables? Both have idCep. I want to get the address data from the cep table and the name and user of the users table.

As I'm working with php, I'm using PDO with the database.

Follow the printout of the tables:

    
asked by anonymous 25.04.2016 / 20:31

3 answers

7

This would be the basics:

SELECT *
  FROM USUARIOS
  JOIN CEP ON CEP.IDCEP = USUARIOS.IDCEP

If you want to limit the columns:

SELECT USUARIOS.*, CEP.cep, CEP.uf, CEP.cidade, CEP.bairro, CEP.logradouro
  FROM USUARIOS 
  JOIN CEP ON CEP.IDCEP = USUARIOS.IDCEP

Consideration:

The zip code number (column cep) is already the table key. So you should not have an IdCep, first for not making sense, second for losing normality.

    
25.04.2016 / 20:44
2
Select CEP.logradouro,
       CEP.bairro,
       CEP.cidade,
       CEP.uf,
       Usuarios.nome,
       Usuarios.usuario
  From CEP
  Inner Joint Usuarios
    on CEP.idCep = Usuarios.idCep
    
25.04.2016 / 20:42
0

Just do join between the two tables

select *
    from Usuario, Cep
    where Usuario.idCep = Cep.idCep
    
25.04.2016 / 20:41