0

我们可以进一步优化这个查询吗:

我需要得到:

SELECT * 
FROM table1 
WHERE (column1, column2) in (SELECT c1, c2 FROM table2);

由于不支持上述查询:

我有以下查询:

SELECT * 
FROM table1 join (SELECT c1, c2 from table2) as table3 
ON table1.column1 = c1 and table1.column2 = c2

编辑:为简单起见,我添加了 table2。但实际上是

select c1, min(c2) from table2 group by c1;
4

3 回答 3

0
SELECT * from table1 t1
WHERE EXISTS (select *
   from table2  ex
   WHERE t1.column1 = ex.c1
     and t1.column2 = ex.c2
   );

更新:这里对于 MIN(c2) 案例:

SELECT * from table1 t1
WHERE EXISTS (select *
   from table2 ex
   WHERE ex.c1 = t1.column1
     and ex.c2 = t1.column2
   )
AND NOT EXISTS (select *
   from table2 nx
   WHERE nx.c1 = t1.column1
     and nx.c2 < t1.column2
   );
于 2013-10-23T16:24:57.787 回答
0

如果我理解正确,不只是

select * from table1 inner join table2 on table1.column1 = table2.c2 and table1.column1 = table2.c2;
于 2013-10-23T16:25:34.437 回答
0

答案是不。
你已经得到了最好的查询。JOIN 通常是最快的选择。但是,缺少列别名会导致语法错误。使用别名和更简单的子句
进行固定和简化:USING

SELECT * 
FROM   table1 t1
JOIN  (
   SELECT c1 AS column1, min(c2) AS column2
   FROM   table2
   GROUP  BY 1
   ) t2 USING (column1, column2)

性能的关键是两个多列索引(唯一或主键约束也有效):

CREATE INDEX t1_mult_idx ON table1 (column1, column2);
CREATE INDEX t2_mult_idx ON table2 (c1, c2);

您可能对 dba.SE 上有关在此类查询中使用索引的困难的相关问题感兴趣。

于 2013-10-23T17:24:34.870 回答