我需要每天運行這個腳本(cron)來更新1個月的反饋總量(至少這是我現在設計的)。這是我的代碼。有人對我應該如何解決這個有更好的想法嗎?也許會改變我對此的方式或優化我的updateMonthlyFeedback.php腳本?MySQL PHP查詢優化 - 反饋
updateMonthlyFeedback.php
session_start();
include("db.php");
$sql="SELECT MAX(uid) as maxUID FROM users";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$maxUID = $row['maxUID'];
for($i=0;$i<$maxUID;$i++){
$sql="SELECT COUNT(*) as negativeCount FROM feedbacks WHERE date_created >= (CURDATE() - INTERVAL 30 DAY) AND type = -1 AND uid = '$i'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$negativeCount = $row['negativeCount'];
$sql="SELECT COUNT(*) as neutralCount FROM feedbacks WHERE date_created >= (CURDATE() - INTERVAL 30 DAY) AND type = 0 AND uid = '$i'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$neutralCount = $row['neutralCount'];
$sql="SELECT COUNT(*) as positiveCount FROM feedbacks WHERE date_created >= (CURDATE() - INTERVAL 30 DAY) AND type = 1 AND uid = '$i'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_array($result);
$positiveCount = $row['positiveCount'];
$sql = "UPDATE feedback_totals SET negativeCount = '$negativeCount', neutralCount = '$neutralCount', positiveCount = '$positiveCount' WHERE uid = '$i'";
$result=mysql_query($sql) or die(mysql_error());
}
MySQL表
CREATE TABLE feedback_totals (
uid VARCHAR(40),
negativeCount int,
neutralCount int,
positiveCount int,
halfStarCount int,
oneStarCount int,
oneHalfStarCount int,
twoStarCount int,
twoHalfStarCount int,
threeStarCount int,
threeHalfStarCount int,
fourStarCount int,
fourHalfStarCount int,
fiveStarCount int,
PRIMARY KEY (uid)
#FOREIGN KEY (uid) REFERENCES users(uid) ON DELETE CASCADE
);
CREATE TABLE feedback_last_month (
uid VARCHAR(40),
negativeCount int,
neutralCount int,
positiveCount int,
halfStarCount int,
oneStarCount int,
oneHalfStarCount int,
twoStarCount int,
twoHalfStarCount int,
threeStarCount int,
threeHalfStarCount int,
fourStarCount int,
fourHalfStarCount int,
fiveStarCount int,
PRIMARY KEY (uid)
#FOREIGN KEY (uid) REFERENCES users(uid) ON DELETE CASCADE
);
CREATE TABLE feedback (
feedback_id INT NOT NULL AUTO_INCREMENT,
uid VARCHAR(40),INDEX (uid),
sender_id VARCHAR(40),
type int, #-1 = neg, 0 = neutral, 1 = positive
starCount VARCHAR(40),
description VARCHAR(80),
date_created timestamp DEFAULT CURRENT_TIMESTAMP,
fromType VARCHAR(40), # buyer or seller
fromUsername VARCHAR(40),
PRIMARY KEY (feedback_id)
#FOREIGN KEY (uid) REFERENCES users(uid) ON DELETE CASCADE
);
那麼顯而易見的第一個答案將是刪除'for'循環,而不是通過uid來限制查詢,'group on' uid。 – 2013-03-25 22:07:37
您確定要從*用戶*中選擇COUNT()而不是計算* feedback *行的數量嗎? – Hazzit 2013-03-25 22:44:34
是的,我更新了這個。剛剛寫了一個快速原型,並沒有測試。只是想擁有一些東西而不是解釋我的問題。 – Toosick 2013-03-25 23:07:22