有两个表,即LongTable和ShortTable。例如,LongTable看起来像这样:
personA | personB
1 | 2
1 | 3
2 | 4
2 | 5
3 | 4
3 | 5
3 | 6
4 | 5
4 | 6ShortTable的内容如下:
PersonA
1
2我想知道如何根据ShortTable中的记录从LongTable中选择记录(请注意,这个表非常长,大约有2.000.000行)。因此,这个特定案例的结果应该是:
personA | personB
1 | 2
1 | 3
2 | 4
2 | 5我从下面的查询开始(但失败了:"Can't reopen table:'ShortTable'"):
SELECT * FROM LongTable
WHERE
personA IN (SELECT * FROM ShortTable)
AND
personB IN (SELECT * FROM ShortTable)重现临时表的代码如下所示。
提前感谢您的指点。
CREATE TABLE LongTable (
personA INT,
personB INT
);
INSERT INTO LongTable VALUES
(1,2),(1,3),(2,4),
(2,5),(3,4),(3,5),
(3,6),(4,5),(4,6);
CREATE TABLE ShortTable (
personA INT
);
INSERT INTO ShortTable VALUES
(1),(2);发布于 2012-10-08 22:44:40
尝尝这个
SELECT DISTINCT l.personA, l.personB
FROM longTable l
INNER JOIN ShortTable s ON l.personA = s.personA 发布于 2012-10-08 22:51:44
您可以使用以下命令:
SELECT * FROM LongTable
WHERE personA IN (SELECT * FROM ShortTable)请注意,运行时间通常取决于表结构(例如索引),而不是查询
发布于 2012-10-08 22:52:11
在MySQL中完成此操作的最快方法是在longTable.personA上创建索引。然后执行以下查询:
select l.personA, l.personB
from longTable l
where exists (select 1 from shortTable s where s.PersonA = l.PersonA limit 1)https://stackoverflow.com/questions/12784043
复制相似问题