从数据库

时间:2016-09-17 09:02:30

标签: sql database

enter image description here

我需要选择'name'属性必须与'seek'属性相同的值。 就像一个匹配的概念,我需要在同一个表中选择'name'attribute ='seek'属性 所以结果将是

name      | seek
HEADPHONE | KETTLE
KETTLE    | HEADPHONE

任何人都可以给我解决方法。我目前正在做我的最后一年项目。谢谢

2 个答案:

答案 0 :(得分:1)

您需要执行SELF JOIN

SELECT a.NAME, 
       a.seek 
FROM   yourtable a 
       JOIN yourtable b 
         ON a.NAME = b.seek 
            AND b.NAME = a.seek 

另一种方法是使用EXISTS

SELECT a.NAME, 
       a.seek
FROM   yourtable a 
WHERE  EXISTS (SELECT 1 
               FROM   yourtable b 
               WHERE  a.NAME = b.seek 
                      AND b.NAME = a.seek) 

答案 1 :(得分:0)

SELECT t1.NAME,
       t1.SEEK
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.NAME = t2.SEEK AND
       t1.SEEK = t2.NAME

如果您只想为每个SEEK / NAME对报告一条记录,那么您可以尝试:

SELECT DISTINCT LEAST(t1.NAME, t1.SEEK),
                GREATEST(t1.NAME, t1.SEEK)
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.NAME = t2.SEEK AND
       t1.SEEK = t2.NAME