试图避免重复查询

时间:2013-03-05 04:05:11

标签: sql

我有桌子A | NAME1 | NAME2 |值|

表B为| name | value |。

表A中的“name1”和“name2”属性是引用表B中“name”的外键。

现在我想要一个像这样的查询函数:

    SELECT value FROM A WHERE name1 IN 
    (SELECT name FROM B WHERE value = '1') AND 
    name2 IN (SELECT name FROM B WHERE value = '1')

这里的问题是,如果我像上面的代码一样,将会有两个来自表B的查询。但实际上我只需要一个查询,SQL中是否存在任何写入

的内容
    SELECT value FROM A WHERE name1,name2 IN (SELECT name FROM B WHERE value = '1') 

如果我想要这样的东西怎么办:

    SELECT value FROM A WHERE name1,name2 IN 
   (SELECT name FROM B ORDER BY value DESC FETCH FIRST 200 ROWS ONLY)

5 个答案:

答案 0 :(得分:0)

可以通过加入来实现吗?

select value from A inner join table b b1 on a.name1 = b1.name inner join table b b2 on a.name2 = b2.name where b1.name = '1' and b2.name = '1'

答案 1 :(得分:0)

你可以使用像SELECT A.value FROM A inner join B on A.name1 = B.name inner join B on A.name2 = B.name where B.name in ('1')这样的联接吗?

答案 2 :(得分:0)

select name, value from b
left outer join (select name1 from a where value = '1') as a1 on 
a1.name1 = b.name
left outer join (select name2 from a where value = '1') as a2 on 
a2.name2 = b.name
where value is not null
/*omit null from left outer join for names not in table b*/

答案 3 :(得分:0)

在SQLServer2005 +中,您可以使用NOT EXISTS + EXCEPT运算符选项

 SELECT A.value 
 FROM A 
 WHERE NOT EXISTS (                   
                   SELECT A.name1
                   UNION
                   SELECT A.name2                   
                   EXCEPT
                   SELECT B.name
                   FROM B 
                   WHERE B.value = '1'                 
                   )

SQLFiddle上的演示

答案 4 :(得分:0)

在表B上创建一个视图并使用它?

Create view B_LIMITED AS SELECT name FROM B WHERE value = '1'

select value from A inner join table b_limited b1 on a.name1 = b1.name inner join table b_limited b2 on a.name2 = b2.name where b1.name = '1' and b2.name = '1'