Concatenate columns and return the relation by SELECT

Asked

Viewed 256 times

6

Suppose I have the following tables and their relations:

Tabela A
    Col 1
    Col 2
    Col 3

Tabela B
    Col 1
    Col 2
    Col 3

Tabela C
    Col 1
    Col 2
    Col 3

Tabela D
    Col 1
    Col 2
    Col 3


Relacionamentos:

A (col 1) ---> B (col 1)  ---> C(col 1) 

Tables A, B and C are listed through the 1st Column.

SELECT 

       Tabela A.Col 2,
       Tabela A.Col 3,
       Tabela B.Col 2,
       Tabela C.Col 3

       FROM Tabela A, Tabela B, Tabela C 

       WHERE Tabela A.Col 1 = Tabela B.Col 1    and     Tabela B.Col 1 = Tabela C.Col 1 

With the above code I could partially get what I need. Now, what I want is to concatenate col 2 and col 3 of Table D in order to be able to make the relation between B(col 1) --- D(col 2 & col 3) and, later, pull col 1 of Table D. Is it possible to do this? If yes, how?

The Final Table would look like this:

Tabela All:
       A.Col 2,
       A.Col 3,
       B.Col 2,
       C.Col 3,
       D.Col 1

2 answers

5

Select simple:

    select * 
      from Tabela A
     inner join Tabela B on A.Col1 = B.Col1
     inner join Tabela C on A.Col1 = C.Col1
      left join Tabela D on B.Col1 = D.Col2+D.Col3

I used left Join for table D here because I understand that it is a composite key and may not bring necessary results to Join. I hope I’ve helped.

2

Well, I found the explanation a little confusing. But in theory if you do Join between the 4 tables, you can put any information in your select. The code below meets you?

   SELECT 
        A.Col 2,
        A.Col 3,
        B.Col 2,
        C.Col 3,
        D.Col 1
   FROM 
       Tabela A
       INNER JOIN Tabela B ON (B.Col1 = A.Col1)
       INNER JOIN Tabela C ON (C.Col1 = A.Col1)
       INNER JOIN Tabela D ON (D.Col1 = A.Col1)
  • He wants to take column 1 of table D together with the others already described, but for this he has to concatenate columns 2 and 3 of table D to relate with column 1 of table B and get a relation between the tables. Your answer still doesn’t quite answer.

  • The last line would be something like: INNER JOIN Tabela D ON ((concatenação de D.Col2 com D.Col3) = B.Col1). I don’t know how to concatenate two columns in SQL, but I need this to solve, I believe.

Browser other questions tagged

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