如何用mysqli来计算今年(多年)某人的年龄

时间:2015-02-04 20:20:05

标签: php mysqli

我试图找出今年有多少孩子转了一个年龄,但我想我需要一个mysql boffin的帮助。这就是我现在所拥有的。

$stmt = $mysqli->prepare("SELECT count(YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5))) FROM schs_students where (YEAR(CURRENT_TIMESTAMP) - YEAR(dob) - (RIGHT(CURRENT_TIMESTAMP, 5) < RIGHT(dob, 5)))=? and gender=1 and house=2");

但它给了我错误的答案。我使用

获得每个孩子的正确年龄
SELECT NOW()-schs_students.dob as age` 

但使用以下内容将计数设为零

SELECT count(NOW()-schs_students.dob) FROM schs_students where (NOW()-schs_students.dob)=? and gender=1 and house=2`

dob在数据库中存储为DATE。基本等式是今年(2015年) - 出生年份(例如2009年给予6)。

那么为什么第二次计数失败?或者为什么第一个给出错误的数字(它看起来像第一个给出了一年的简短)?

我正在使用的完整代码循环如下

for ($i=6;$i<14;$i++)
{
    $stmt = $mysqli->prepare("SELECT count(NOW()-schs_students.dob) FROM schs_students where (NOW()-schs_students.dob)=? and gender=1 and house=2");
    $stmt->bind_param("i",$i);
    $stmt->execute();
    $result = $stmt->get_result();
    $row = $result->fetch_row();
    if ($row)
    {
        $total=$row[0];
        echo "<td>{$total}</td>";
        //echo $total." of them are {$i} this year.<br/>";
    }
    $stmt->close();
}

1 个答案:

答案 0 :(得分:4)

在MySQL中只需要一个函数,即TIMESTAMPDIFF

 SELECT TIMESTAMPDIFF(YEAR, '1970-06-01 05:45:33', CURRENT_TIMESTAMP);

现在有一些学生今天>

SELECT count(*) FROM schs_students where 
TIMESTAMPDIFF(YEAR, schs_students.dob, CURRENT_TIMESTAMP)=? and gender=1 and house=2

显然,schs_students.dob必须DATETIME而不仅仅是char

这个年满一定年龄的学生数量会有点困难...实际上一年,我猜这个截止日期是12月31日,所以请使用该日期:

SELECT count(*) FROM schs_students where 
TIMESTAMPDIFF(YEAR, schs_students.dob, concat(Year(NOW()),'-12-31'))=? and gender=1 and house=2