简体   繁体   English

你如何将这3个mySQL查询合并为一个?

[英]How do you combine these 3 mySQL queries into one?

The schematic code of what I am trying to do: 我想要做的示意代码:

INPUT VAR inputOne; (First input of the desired statement)
INPUT VAR inputTwo; (Second input of the desired statement)
INPUT VAR inputThree; (Third input of the desired statement)

-

VAR repResult = getResult("SELECT * FROM `representatives` WHERE `rID` = inputOne LIMIT 1;")
VAR evResult = getResult("SELECT `events`.`eID` FROM `events` WHERE `eventDateTime` = inputTwo LIMIT 1;")

if (repResult != null && evResult != null) {
    execureQuery("INSERT INTO `votes` (`representatives_rID`, `events_eID`, `voteResult`) VALUES(inputOne,evResult.eID,inputThree);");
}

It is quite slow, when I execute them in separated statement, especially because there are ~1.000.000 that needs to be checked and inserted. 当我在单独的语句中执行它们时,它非常慢,特别是因为需要检查和插入~1.000.000。 I was wondering, if there is any alternative, one-query way of doing this. 我想知道,如果有任何替代方案,可以采用一种查询方式。

You can use INSERT-SELECT syntax to accomplish this: 您可以使用INSERT-SELECT语法来完成此任务:

INSERT INTO `votes` (`representatives_rID`, `events_eID`, `voteResult`) 
select inputOne, `events`.`eID`, inputThree FROM `events` WHERE `eventDateTime` = inputTwo LIMIT 1

The above combines all three params into one INSERT-SELECT statement where the results of the select are sent to the insert. 上面将所有三个参数组合成一个INSERT-SELECT语句,其中select的结果被发送到插入。

See: Insert into ... values ( SELECT ... FROM ... ) for select-insert statement. 请参阅:为select-insert语句插入...值(SELECT ... FROM ...)

Yes, you can put these statements into 1 Stored Procedure (which returns 2 resultsets and performs 1 insert), but no, this probably wouldn't help. 是的,您可以将这些语句放入1个存储过程(返回2个结果集并执行1次插入),但不是,这可能无济于事。 Because 3 SQL statements are not a big amount of network traffic, and because Stored Procedures are slow in MySQL. 因为3个SQL语句不是很大的网络流量,并且因为存储过程在MySQL中很慢。

Is rID a primary key? rID是主键吗? Does the first query extract big fields you don't really need? 第一个查询是否提取了您不需要的大字段?

Is there a unique index on eventDateTime? eventDateTime上有唯一索引吗? If the table is not InnoDB, the index should explicitly include eID, so it becomes a covering index. 如果表不是InnoDB,则索引应明确包含eID,因此它将成为覆盖索引。

After making those keys, you can drop LIMIT 1 . 制作这些键后,您可以删除LIMIT 1

Are rID and eID datatypes as small as possible? rID和eID数据类型是否尽可能小?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM