2

我有表 A 作为 |name1|name2|value|

表 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)

?

4

5 回答 5

0

In SQLServer2005+ you can use option with NOT EXISTS + EXCEPT operators

 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'                 
                   )

Demo on SQLFiddle

于 2013-03-05T07:21:47.313 回答
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*/
于 2013-03-05T04:39:52.927 回答
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'

于 2013-03-05T04:11:03.527 回答
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'
于 2013-03-05T08:04:19.833 回答
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')吗?

于 2013-03-05T04:18:12.453 回答