我创建了一个使用php和mysql的Web服务来插入和返回我的应用程序的数据。用户的一个主要抱怨是响应太慢,我同意,因为完成任务需要5-10秒。最初认为这是托管性能问题,但并没有产生任何影响(godaddy与AWS)。
查看我的php文件中的SQL代码,我认为这是问题所在。我想重写以提高速度。我相信问题是我使用时间戳,并且返回时我总是寻找最大值(时间戳)。
这是我输入的SQL语句:
$insert = mysql_query("INSERT INTO meals (user, date, meal, timeStamp, food) VALUES ('$user','$date','$meal','$timeStamp','$food')");
这是我的返回SQL语句:
$query = mysql_query ("SELECT * FROM meals WHERE user = '$user' AND date = '$date' AND meal = '$meal' AND timeStamp = (SELECT MAX(`timeStamp`)FROM meals WHERE user = '$user' AND date = '$date' AND meal = '$meal')");
使用UPDATE或类似代码而不是使用时间戳会更好吗?还有其他建议吗?
答案 0 :(得分:3)
这是您的查询:
SELECT *
FROM meals
WHERE user = '$user' AND date = '$date' AND meal = '$meal' AND
timeStamp = (SELECT MAX(`timeStamp`)
FROM meals
WHERE user = '$user' AND date = '$date' AND meal = '$meal'
);
假设您只想要一行,第一个简化是:
SELECT *
FROM meals
WHERE user = '$user' AND date = '$date' AND meal = '$meal'
ORDER BY timestamp desc
LIMIT 1;
接下来,索引将有助于此查询。事实上,meals(user, date, meal, timestamp)
上的索引适用于where
和order by
。这应该会提高绩效。