Doubt about using the inner join

4

I have 4 tables in my database

Tabela Cadastro
     - idCadastro(PK)
     - IP

Tabela Porta
     - idPorta(PK)
     - numero porta
     - idSwitch(FK)

Tabela Porta_has_Cadastro
     - idCadastro(FK)
     - idPorta(PK)

//Observação: Relaçao n para n entre cadastro e porta.

Tabela Switch
     - idSwitch
     - Modelo

I want the information to look like this:

IP  ----  PORTA  ----  SWITCH

Example:

O ip 192.168.0.1 esta na porta 1 do Switch HP
O ip 192.168.0.2 esta na porta 2 do Switch Dell
    
asked by anonymous 23.10.2015 / 13:51

2 answers

5

Try this query:

SELECT cad.IP,
        por.numero_porta,
        swi.modelo
FROM cadastro cad
  INNER JOIN Porta_has_Cadastro phc ON cad.idCadastro = phc.idCadastro
  INNER JOIN Porta por ON phc.id_porta = por.id_porta
  INNER JOIN Switch swi ON por.id_switch = swi.id_switch

Then if you want to bring the complete sentence directly from the database, you can use string concatenation, but it depends on the data type of each column, it may be necessary to convert the type, since the concatenation depends on the database, , can be + for Sql Server and || for Postgres.

    
23.10.2015 / 14:08
1

[Assuming MSSQLServer]

Without specifying which of the two ways either, you can do the following:

SELECT 'O ip ' + C.IP + ' esta na porta ' + CAST(P.numero_porta AS nvarchar) + ' do Switch ' + s.Model
FROM dbo.Switch as s
     inner join dbo.Porta as P on p.idSwitch = s.idSwitch
     inner join dbo.Porta_has_Cadastro as PhC on PhC.idPorta = p.idPorta
     inner join dbo.Cadastro as C on C.idCadastro = PhC.idCadastro;

Or else:

SELECT C.IP, P.numero_porta, s.Model
FROM dbo.Switch as s
     inner join dbo.Porta as P on p.idSwitch = s.idSwitch
     inner join dbo.Porta_has_Cadastro as PhC on PhC.idPorta = p.idPorta
     inner join dbo.Cadastro as C on C.idCadastro = PhC.idCadastro;

See a example in SQLFiddle .

    
23.10.2015 / 14:13