You can use two columns of the same table in a WHERE [closed]

1

In a select I can use in the where to filter the results, two columns of the same table?

Ex:

Select id, idpai, nome FROM tabela Where id=idpai
    
asked by anonymous 14.09.2016 / 08:01

3 answers

2

You have already answered your own question.

  

I would have some way where at the time that the select rotate I get the value of a specific column and then apply direct mo WHERE?

" At the time the select run " ... select will try to run where but what you really need is to run another select by applying where according to the return of this first.

If the solution you are looking for is to return only fields that fit into a set of values, then you can do select using the keyword IN .

select ID, valor 
from tabela 
where valor in (8902, 3789, 8452, 7172, 1239);

If you still "need" to do this query, you are learning the concept a little bit wrong. In SQL, it is common to return rows , according to values within columns .

Anyway, I hope I have helped.

    
14.09.2016 / 13:16
0

You can generate a sub query. An example:

SELECT ID, valor FROM tabela WHERE valor IN (SELECT valor FROM tabela2 WHERE valor = [parametro]);

The sub query should return only one column, which will be justly used as the filter in the main column. In the sub query I put the field / column value again, but it could be another, the caveat is with the return of the sub query, it should only return a single column.

    
14.09.2016 / 14:31
0

Yes, in general there is how to do the relationship with the same table but if you have to do this, review the structure of the data because something is wrong.

You can use JOIN in the same table, as follows:

SELECT 
t1.id as id_categoria_pai,
t1.nome as nome_categoria_pai,
t2.id,
t2.nome
FROM teste t1
LEFT JOIN teste t2 ON t2.id = t1.idpai

See working in sqlfiddle

    
14.09.2016 / 19:10