我正在开发聊天应用。
我有两个表格messages
和message_archives
两个表格列相同。
我的messages
表包含1,00,000条记录。我想将记录移至message_archives
来自超过30天的邮件。
我的代码:
$privateMsg = mysql_query("SELECT * FROM messages WHERE created < DATE_SUB(curdate(), INTERVAL 30 DAY)");
if(mysql_num_rows($privateMsg)){
while($getPrivateMsg=mysql_fetch_array($privateMsg)){
mysql_query("INSERT INTO message_archives SET user_id='".$getPrivateMsg['user_id']."', friend_id='".$getPrivateMsg['user_id']."', message='".$getPrivateMsg['message']."', is_view='0', created='".$getPrivateMsg['created']."'");
mysql_query("DELETE FROM messages WHERE id='".$getPrivateMsg['id']."'");
}
echo "Message move to archives older than 30 days";
}else{
echo "Error!! message not moved!!!.";
}
以上代码完美运行。但我需要自定义我的代码。我在单个查询中需要它。是否有单一查询的快捷方式?
答案 0 :(得分:6)
我建议不要循环结果集来移动它们,而只是使用单个INSERT
语句和单个DELETE
语句:
INSERT INTO message_archives (user_id, friend_id, message, is_view, created)
SELECT user_id, user_id, message, 0, created
FROM messages
WHERE created < DATE_SUB(curdate(), INTERVAL 30 DAY)
DELETE FROM messages
WHERE created < DATE_SUB(curdate(), INTERVAL 30 DAY)
BTW - 您确定要为user_id
和user_id
字段插入friend_id
吗?也许这是一个错字。