Help in Sql that queries 2 fields from the same table

0

I have the following problem to solve:

I need to make a Sql that queries an X table

"Tabela X":
id coluna1 coluna2 

"Tabela 2":
id coluna1 coluna2 coluna3.

In "Table X" column1 and column2 are foreign keys of "table 2" both with different values.

In Sql I need to return the id of the tableX the id of table 2 and any column of table two for the 2 foreign key fields.

Data Extent:

Tabela X:

id   coluna1     coluna2   
1     1           2
2     2           1           
3     3           1
4     4           2

column1 and column 2 are the primary key of table 2.

Tabela 2:

id    coluna1       coluna2      coluna 3
1     TB2val1      TB2outro1     TB2aux1
2     TB2val2      TB2outro2     TB2aux2 
3     TB2val3      TB2outro3     TB2aux3
4     TB2val4      TB2outro4     TB2aux4

I tried to do this:

select  tx.id,tx.coluna1,tx.coluna2,t2.coluna1   from tabelaX tx,tabela2 t2 
where tx.id=t2.id group by tx.id,tx.coluna1,tx.coluna2,t2 

But I could not complete the sql because I need to join the other query in the select and I could not find how to do it.

I would need a return on select with these columns:

idTabela1   idTabela2 idTabela2  tabela2.coluna1  tabela2.coluna1

In the first result it would have to look like this:

Result of the first row of the select that I need: 1 1 2 TB2val1 TB2val2

I have researched here and probably this question is solved with a Union select.

    
asked by anonymous 15.03.2018 / 14:57

1 answer

0

Since coluna1 and coluna2 are primary and foreign keys in tabelaX and tabela2 , respectively, you need to use these fields in JOIN :

SELECT 
    tx.id as idTabela1, t2.id as idTabela2, tx.coluna1 as coluna1, tx.coluna2 as coluna2
FROM 
    tabelaX tx
JOIN 
    tabela2 t2 ON tx.coluna1 = t2.coluna1 AND tx.coluna2 = t2.coluna2
    
15.03.2018 / 15:15