我们可以进一步优化此查询:
我需要得到:
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;
答案 0 :(得分: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
);
答案 1 :(得分:0)
如果我理解正确,不仅仅是
select * from table1 inner join table2 on table1.column1 = table2.c2 and table1.column1 = table2.c2;
答案 2 :(得分: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)
性能的关键是两个multi-column indices(唯一或主键约束也起作用):
CREATE INDEX t1_mult_idx ON table1 (column1, column2);
CREATE INDEX t2_mult_idx ON table2 (c1, c2);
您可能对this related question on dba.SE感兴趣的是在此类查询中使用索引时出现的问题。