首页 文章

SQL高级子选择查询

提问于
浏览
2

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

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

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

现在我想扩展一下 .

在表1中,我想返回结果,其中field1和field2以及field3在select(field1,field2,field3 from table2 where clause ...)

这怎么可能?

提前致谢 .

例 .

TABLE1

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

TABLE 2

2       3      4 
4       5      6

我想返回2个结果 .

5 回答

  • 0

    如果我了解您的需求,您可以尝试:

    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

    就像马克指出的那样,你想做的是 INNER JOIN .

    但是(这只是FYI,你绝对应该使用Marco的解决方案)它也可以简单地使用大括号 .

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

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

  • 1

    你可以使用临时表

    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

    对于大多数情况,请避免使用 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
    

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

  • 6

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

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

相关问题