获取密钥存在的引用的值

时间:2016-06-15 11:09:34

标签: sql sql-server

我有一个看起来像这样的表:

ref    key        val
--------------------------
1      Include    Yes
1      Color      Green
1      Shape      Square
2      Include    No
2      Color      Red
2      Shape      Circle

如果Include密钥存在且值为Yes,我希望获得具有相同参考的所有值。

因此对于上面的例子,结果应该是:

ref    key        val
--------------------------
1      Include    Yes
1      Color      Green
1      Shape      Square

这是我到目前为止所做的:

select *
from ref_table
where ref in
(
  select ref
  from ref_table
  where key = 'Include' and val = 'Yes'
)

这似乎也有效:

with included
as
(
  select ref
  from ref_table
  where key = 'Include' and val = 'Yes'
)

select *
from ref_table
where ref in
(
  select * from included
)

只是想知道是否有更好(更简单)的方法来做到这一点。

2 个答案:

答案 0 :(得分:3)

您可以使用EXISTS()

SELECT * FROM ref_table t
WHERE EXISTS(SELECT 1 FROM ref_table s
             WHERE t.ref = s.ref and s.key = 'Include' and s.val = 'Yes')

我总是喜欢这种方法超过IN(),大部分时间它表现得更好(存在等待第一条记录返回),为此目的也更清楚。 IN()可能会返回NULL值时出现问题。

另一种方式是INNER JOIN

SELECT t.* FROM ref_table t
INNER JOIN ref_table s
 ON(t.ref = s.ref and s.key = 'Include' and s.val = 'Yes')

答案 1 :(得分:0)

使用OUTER APPLY的另一种方法,但我想它并不简单:

SELECT r.*
FROM ref_table r
OUTER APPLY (
    SELECT DISTINCT ref 
    FROM ref_table 
    WHERE [key] = 'Include' and val = 'Yes') p
WHERE p.ref = r.ref