MySQL - 优化两个链接表的选择
我有两个 MySQL 表,states 和 trans:
states (200,000 个条目)看起来像:
id (INT) - also the primary key
energy (DOUBLE)
[other stuff]
trans (14,000,000 个条目)看起来像:
i (INT) - a foreign key referencing states.id
j (INT) - a foreign key referencing states.id
A (DOUBLE)
我想用 trans.A > 搜索 trans 中的所有条目。 30.(比如说),然后从每个匹配条目引用的(唯一)状态返回能量条目。所以我用两个中间表来做:
CREATE TABLE ij SELECT i,j FROM trans WHERE A>30.;
CREATE TABLE temp SELECT DISTINCT i FROM ij UNION SELECT DISTINCT j FROM ij;
SELECT energy from states,temp WHERE id=temp.i;
这似乎可行,但是有没有办法在没有中间表的情况下做到这一点?当我尝试直接从 trans: 使用单个命令创建临时表时,
CREATE TABLE temp SELECT DISTINCT i FROM trans WHERE A>30. UNION SELECT DISTINCT j FROM trans WHERE A>30.;
它花费了更长的时间(大概是因为它必须搜索大型 trans 表两次。我是 MySQL 新手,我似乎找不到等效的问题并在互联网上回答。 非常感谢, 基督教
I have two MySQL tables, states and trans:
states (200,000 entries) looks like:
id (INT) - also the primary key
energy (DOUBLE)
[other stuff]
trans (14,000,000 entries) looks like:
i (INT) - a foreign key referencing states.id
j (INT) - a foreign key referencing states.id
A (DOUBLE)
I'd like to search for all entries in trans with trans.A > 30. (say), and then return the energy entries from the (unique) states referenced by each matching entry. So I do it with two intermediate tables:
CREATE TABLE ij SELECT i,j FROM trans WHERE A>30.;
CREATE TABLE temp SELECT DISTINCT i FROM ij UNION SELECT DISTINCT j FROM ij;
SELECT energy from states,temp WHERE id=temp.i;
This seems to work, but is there any way to do it without the intermediate tables? When I tried to create the temp table with a single command straight from trans:
CREATE TABLE temp SELECT DISTINCT i FROM trans WHERE A>30. UNION SELECT DISTINCT j FROM trans WHERE A>30.;
it took a longer (presumably because it had to search the large trans table twice. I'm new to MySQL and I can't seem to find an equivalent problem and answer out there on the interwebs.
Many thanks,
Christian
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这应该可以解决问题,我已经在 SQL Server 2008 中测试了它,所以希望它也能在 MySQL 中工作。
this should do the trick, I've tested it in SQL Server 2008, so hopefully it works in MySQL too.
好的...在 Axarydax 和其他人的帮助下,我使用了(本质上等效的)命令:
如果我有 i、j 和 A 上的索引,该命令的运行速度足够快。
OK... with a bit of help from Axarydax and others, I use the (essentially equivalent) command:
which works fast enough if I've got an index on i,j and A.