简体   繁体   中英

Condition for select statement using SQL Server 2008 R2

I have a table as shown below:

Example :

Table:

CREATE TABLE testo
(
 namea VARCHAR(10),
 nameb VARCHAR(10),
 details VARCHAR(10)
)

With some records:

INSERT INTO testo VALUES('A','C','xyz');
INSERT INTO testo VALUES('A','B','oxo');
INSERT INTO testo VALUES('B','D','ner');
INSERT INTO testo VALUES('X','Y','tye');
INSERT INTO testo VALUES('Z','U','txt');
INSERT INTO testo VALUES('Y','N','str');

namea nameb details
-------------------
 A      C   xyz
 A      B   oxo
 B      D   ner
 X      Y   tye
 Z      U   txt
 Y      N   str

Note : I want to show those records where nameb exists in namea and also want to show that record where namea belongs to that nameb which is present in namea .

Expected Result:

namea  nameb  details
---------------------
 A      B       oxo
 B      D       ner
 X      Y       tye
 Y      N       str

For which I have tried:

 select * from testo
 where nameb in (select namea from testo);

But getting only:

namea  nameb  details
---------------------
 B      D       ner
 Y      N       str

SQL Fiddle:-> http://sqlfiddle.com/#!2/0a3bb2/1

select * 
from testo
where 
    nameb in (select namea from testo)
    or namea in (select nameb from testo)

试试这个:SELECT * FROM testo WHERE namea IN(SELECT nameb FROM testo)union SELECT * FROM testo WHERE nameb IN(SELECT namea FROM testo);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM