[英]Insert If No Exists and Get Insert Id in PHP&MySql
I'm developing a PHP script and I just want to know if I can make this code piece with better performance. 我正在开发PHP脚本,我只想知道是否可以使此代码段具有更好的性能。
I have to make 2 mysql queries to complete my task. 我必须进行2个mysql查询才能完成任务。 Is there any other way to complete this with better performance?
还有其他方法可以更好地完成此操作吗?
$language = "en";
$checkLanguage = $db->query("select id from language where shortName='$language'")->num_rows;
if($checkLanguage>0){
$languageSql = $db->query("select id from language where shortName='$language'")->fetch_assoc();
$languageId = $languageSql['id'];
}else{
$languageSql = $db->query("insert into language(shortName) values('$language')");
$languageId = $db->insert_id;
}
echo $languageId
You can improve your performance, by storing the stamtement object to a variable, this way it will be one less query: 通过将stamtement对象存储到变量中,可以提高性能,这样可以减少查询:
$checkLanguage = $db->query("select id from language where shortName='$language'");
if($checkLanguage->num_rows >0){
$languageSql = $checkLanguage->fetch_assoc();
$languageId = $languageSql['id'];
}else{
$languageSql = $db->query("insert into language(shortName) values('$language')");
$languageId = $db->insert_id;
}
echo $languageId
or second option you add unique constraint to language
and shortName
. 或第二个选项,您可以向
language
和shortName
添加唯一约束。
If you insert a duplicate it will throw an error, if not it will insert, this way you keep only one query the INSERT one, but you might need a try catch for duplicates. 如果插入重复项,则会引发错误,否则将引发错误,这样,您只保留一个查询,即INSERT一个查询,但是您可能需要尝试捕获重复项。
Why not just do something like this: 为什么不做这样的事情:
$language = "en";
$dbh = $db->query("INSERT IGNORE INTO `language` (`shortName`) VALUES ('{$language}');");
$id = $db->insert_id;
echo (($id !== 0) ? $id : FALSE);
This will perform your logic in a single query, and return the id, or false on a duplicate. 这将在单个查询中执行您的逻辑,并返回ID,如果重复则返回false。 It is generally better to resolve database performance issues in the SQL rather than in PHP, because about 65% of your overhead is in the actual connection to the database, not the query itself.
通常,最好用SQL而不是PHP解决数据库性能问题,因为大约65%的开销是在与数据库的实际连接中,而不是查询本身。 Reducing the number of queries you run typically has a lot better impact on performance than improving your scripting logic revolving around them.
减少运行的查询数量通常比改善围绕它们的脚本逻辑对性能有更好的影响。 People that consistently rely on ORM's often have a lot of trouble with this, because cookie cutter SQL is usually not very performant.
一直依赖ORM的人对此经常遇到很多麻烦,因为cookie切割器SQL通常性能不高。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.