简体   繁体   English

如何构建更复杂的mysql查询以进行优化

[英]How to construct a more complex mysql query for optimization

I have this lovely piece of code that I want to optimize: 我有这个可爱的代码片段,我想优化:

$result = mysql_query("select day from cities where name='St Charles'");
$row = mysql_fetch_assoc($result);
$day = $row['day'];

$result = mysql_query("select id,durability from goods_meta_data");

while($row = mysql_fetch_assoc($result)) {
    mysql_query("delete from possessions where day_created<" . ($day-$row[durability]) . " and good_id=" . $row['id']);
}

It deletes rows from the table 'possessions' if the possession has expired. 如果占有已过期,它会从表'所有'中删除行。 Whether or not the possession has expired is determined by values in the tables 'goods' and 'cities'. 占有权是否已过期取决于表格“商品”和“城市”中的值。 Specifically, the age of the good = day-day_created, if the age of the good is more than its durability, then it is expired. 具体来说,商品的年龄= day-day_created,如果商品的年龄超过其耐久性,那么它就会过期。 (Every possession is a type of good, and every good has a unique durability.) (每一种财产都是一种商品,每种商品都具有独特的耐久性。)

This code works, but I feel like this could be done in a single query. 这段代码有效,但我觉得这可以在一个查询中完成。 The latency to the mysql server is particularly large, so doing this operation in less queries would be very beneficial. mysql服务器的延迟特别大,因此在较少的查询中执行此操作将非常有益。

How do I do that? 我怎么做? Any ideas? 有任何想法吗?

Also, if you can point me to any useful resources where I can learn about taking better advantage of relational databases in this manner, it would be helpful. 另外,如果您能指出我可以学习如何以这种方式更好地利用关系数据库的任何有用资源,那将会很有帮助。

Assuming your first query returns a single result, then this should work: 假设您的第一个查询返回单个结果,那么这应该工作:

DELETE p 
FROM possessions p
    INNER JOIN goods_meta_data gmd ON p.good_id = gmd.id
    INNER JOIN cities c ON c.name = 'St Charles'
WHERE p.day_created < c.day - gmd.durability 

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

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