2012-04-10 82 views
2

我想扩大这个简单的子选择:SQL先进的子选择查询

Select * from table1 where pkid in (select fkid from table2 where clause...) 

上面的逻辑很简单 - 让我在PKID包含在从返回的子集的所有行table1中具有where子句的子选择查询。它运作良好,因为只有1个字段被返回。

现在我想对此进行扩展。

在表1中我要返回结果,其中FIELD1和选择Field2和Field3的(字段1,字段2,字段3从表2 where子句...)

这怎么可能?

在此先感谢。

例子。

TABLE1

FIELD1 FIELD2 FIELD3  
1  2  3  
2  3  4  
4  5  6 

表2

2  3  4 
4  5  6 

我要回2分的结果。

回答

6

如果我知道你需要什么,你可以尝试:

SELECT t1.field1, t1.field2, t1.field3 FROM table1 t1 
INNER JOIN table2 t2 
    ON t1.field1 = t2.field1 
    AND t1.field2 = t2.field2 
    AND t1.field3 = t2.field3 
    AND t2.... // Use this as WHERE condition 
+0

呀,对不起,如果这个问题是很难理解的。但我认为你已经钉住了它。 – 2012-04-10 14:53:30

0

你可以使用一个临时表使用IN在大多数情况下是这样

select field1, field2, field3 into #tempTable from table2 where clause... 

select * from table 1 
where filed1 in (select field1 from #tempTable) 
and filed2 in (select field2 from #tempTable) 
and filed3 in (select field3 from #tempTable) 
0

避免。这是非常有限的。

我更喜欢在大多数情况下使用JOIN。

SELECT 
    * 
FROM 
    yourTable 
INNER JOIN 
    (SELECT c1, c2, c3 FROM anotherQuery) AS filter 
    ON yourTable.c1 = filter.c1 
    AND yourTable.c2 = filter.c2 
    AND yourTable.c3 = filter.c3 

你没有提到的发动机

0

(确保过滤器使用DISTINCTGROUP BY如果需要返回c1, c2, c3独特的组合),所以我会承担的SQL Server。 此查询会告诉你什么是这两个表

select FIELD1, FIELD2 from table1 
intersect 
select FIELD1, FIELD2 from table2 
1

像马可指出,你想要做什么是INNER JOIN

但是(这只是供参考,你应该使用Marco的解决方案),也可以简单地使用大括号。

Select * 
from table1 
where (field1, field2, field3) in (select field1, field2, field3 from table2 where clause...) 

至少在MySQL(是不是这个问题的标记与MySQL?)

+0

这假设很多。 ORACLE可以做到这一点,SQL SERVER不能,例如。 – MatBailie 2012-04-10 15:01:59

+0

@Dems:它是有效的标准SQL,如果问题只有'sql'标记,那肯定是可以接受的。 – onedaywhen 2012-04-10 15:11:49

+0

@onedaywhen - 在我的评论之后添加了“至少在MySQL中(这个问题不是用MySQL标记的这个问题?没有这个补充,答案意味着它适用于所有版本的SQL,这是错误的。 – MatBailie 2012-04-10 15:13:17