A        B        C
ppp 测试 料件 (第一行)
测试 NULL 产品  (第二行)表名T
我想得到结果如上 条件是  A='ppp' or B='ppp'
现在想加个条件是 或者 第一行B=第二行A 当然不是只有2行数据,A是主键,请问这个条件如何写呢?

解决方案 »

  1.   

    可以使用自连接或者嵌套查询来实现,比如:
    SELECT a.* 
    FROM T a LEFT JOIN T b ON A.主键=B.主键
    WHERE a.第一行=B.第二行
      

  2.   

    ;with t as
    (
    select * from tb where  A='ppp' or B='ppp'
    union all
     select b.* from t join tb as b where t.b=b.a
    )
    select * from t
      

  3.   

    select * from t as a
    where A='ppp'
        or B='ppp'
        or Exists(Select 1 from t as x
                      where x.A=a.B)
        or Exists(Select 1 ffom t as x
                      where x.B=a.A)
      

  4.   

    (Ben)的语句可以是可以,但是查出的结果多了 
    123       InstructionBook-01       套餐
    AAAAA       GLG-001                       产品
    deedffde      测试                            料件
    GLG-001       NULL                        产品
    Instruct      NULL                        产品
    ppp       测试                            料件
    yy        う                           料件
    う        NULL                       产品
    测试      NULL                       产品
    应该只有3行,就是字段包含测试的那三行
      

  5.   

    ;with Result_tmp as (
        select row_number()Over(Order by getdate()) as Rank,* from t
    )Select Distinct A,B,C from Result_tmp as a
        Where a.A='ppp' Or a.B='ppp'
            Or Exists(select 1 from Result_temp as x
                          Where x.Rank=a.Rank-1
                              And x.A=a.B
                   )
            Or Exists(select 1 from Result_temp as x
                          Where x.Rank=a.Rank+1
                              And x.B=a.A
                   )