好的,我会解决的:我是一个比数据库更好的编码器,而且我想知道关于“最佳实践”的想法是关于在SQL查询中还是在SQL查询中进行“简单”计算的。代码,例如此MySQL示例(我没有编写它,我只需要维护它!)-这将返回用户名,以及用户从上次事件开始的年龄。
SELECT u.username as user,
IF ((DAY(max(e.date)) - DAY(u.DOB)) < 0 ,
TRUNCATE(((((YEAR(max(e.date))*12)+MONTH(max(e.date)))
-((YEAR(u.DOB)*12)+MONTH(u.DOB)))-1)/12, 0),
TRUNCATE((((YEAR(max(e.date))*12)+MONTH(max(e.date))) -
((YEAR(u.DOB)*12)+MONTH(u.DOB)))/12, 0)) AS age
FROM users as u
JOIN events as e ON u.id = e.uid
...
与在代码中进行“繁重”的提升相比:
查询:
SELECT u.username, u.DOB as dob, e.event_date as edate
FROM users as u
JOIN events as e ON u.id = e.uid
码:
function ageAsOfDate($birth, $aod)
{ //expects dates in mysql Y-m-d format...
list($by,$bm,$bd) = explode('-',$birth);
list($ay,$am,$ad) = explode('-',$aod);
//Insert Calculations here
...
return $Dy; //Difference in years
}
echo "Hey! ". $row['user'] ." was ". ageAsOfDate($row['dob'], $row['edate']) . " when we last saw him.";
我敢肯定,在像这样的简单情况下,不会有太大的区别(除了我必须像第一个那样对查询进行更改时的恐怖感),但我认为这使我更清楚了我在寻找。
谢谢!