3

我想扩展这个简单的子选择:

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

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

现在我想对此进行扩展。

在表 1 中我想返回结果 where field1 and field2 and field3 in select (field1, field2, field3 from table2 where 子句...)

这怎么可能?

提前致谢。

例子。

表格1

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

表 2

2       3      4 
4       5      6

我想返回 2 个结果。

4

5 回答 5

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
于 2012-04-10T14:52:18.507 回答
1

就像 Marco 指出的那样,您想要做的是一个INNER JOIN.

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

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

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

于 2012-04-10T14:59:17.123 回答
0

你可以使用临时表

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)
于 2012-04-10T14:52:32.993 回答
0

避免IN在大多数情况下使用这种情况。这是非常有限的。

在大多数情况下,我更喜欢使用 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

(确保过滤器返回c1, c2, c3使用的唯一组合DISTINCTGROUP BY必要时)

于 2012-04-10T14:53:48.770 回答
0

你没有提到引擎,所以我假设 SQL Server。此查询将向您显示两个表上的内容

select FIELD1, FIELD2 from table1 
intersect
select FIELD1, FIELD2 from table2 
于 2012-04-10T14:55:42.320 回答