简体   繁体   中英

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. (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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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