How to select data from different tables

Asked

Viewed 439 times

3

How to make a select picking a field from each table?

I want to get the text field from 4 different tables, as I should?

  • Could put the tables and explain the purpose of the consultation

  • 1

    @Felipe - No select,vc need to indicate which table is the field and no from you will marry the tables. Edit your post and place tables that are easier to help you.

2 answers

10


I believe that’s what you want:

tables:

TB_USUARIO  |   TB_ENDERECO         | TB_CEP        | TB_CIDADE
------------|-----------------------|---------------|-----------
ID_USUARIO  |   ID_ENDERECO         | ID_CEP        | ID_CIDADE
NOME        |   ID_USUARIO          | ID_ENDERECO   | ID_CEP
                ENDERECO            | CEP           | CIDADE

Method 1:

SELECT 
    TB_USUARIO.ID_USUARIO,
    TB_USUARIO.NOME,
    TB_ENDERECO.ID_ENDERECO,
    TB_ENDERECO.ID_USUARIO,
    TB_ENDERECO.ENDERECO,
    TB_CEP.ID_CEP,
    TB_CEP.ID_ENDERECO,
    TB_CEP.CEP,
    TB_CIDADE.ID_CIDADE,
    TB_CIDADE.ID_CEP,
    TB_CIDADE.CIDADE
    FROM TB_USUARIO
    INNER JOIN TB_ENDERECO 
    ON TB_ENDERECO.ID_USUARIO = TB_USUARIO.ID_USUARIO
    INNER JOIN TB_CEP
    ON TB_CEP.ID_ENDERECO = TB_ENDERECO.ID_ENDERECO
    INNER JOIN TB_CIDADE
    ON TB_CIDADE.ID_CEP = TB_CEP.ID_CEP

Method 2: Adding nickname to tables:

SELECT 
    usu.ID_USUARIO,
    usu.NOME,
    en.ID_ENDERECO,
    en.ID_USUARIO,
    en.ENDERECO,
    cep.ID_CEP,
    cep.ID_ENDERECO,
    cep.CEP,
    cid.ID_CIDADE,
    cid.ID_CEP,
    cid.CIDADE
    FROM TB_USUARIO usu
    INNER JOIN TB_ENDERECO en ON (end.ID_USUARIO = usu.ID_USUARIO)
    INNER JOIN TB_CEP cep ON (cep.ID_ENDERECO = en.ID_ENDERECO)
    INNER JOIN TB_CIDADE cid ON (cid.ID_CEP = cep.ID_CEP)

Method 3: Returning all table fields:

SELECT * FROM TB_USUARIO usu
    INNER JOIN TB_ENDERECO end ON (end.ID_USUARIO = usu.ID_USUARIO)
    INNER JOIN TB_CEP cep ON (TB_CEP.ID_ENDERECO = end.ID_ENDERECO)
    INNER JOIN TB_CIDADE cid ON (TB_CIDADE.ID_CEP = TB_CEP.ID_CEP)

These are examples of how it can be done, there are several others!

  • 1

    Just what I needed, was in doubt how to do!

4

It can be done that way:

SELECT a.name, b.term_taxonomy_id 
    FROM wp_terms a, wp_term_taxonomy b 
    WHERE a.term_id=b.term_id
  • 1

    Thanks Fernando, the visualization was better.

Browser other questions tagged

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