我正在努力了解今年有多少孩子达到一定年龄,但我认为我需要mysql研究人员的帮助。这就是我现在所拥有的。
$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`
CCD_ 1作为CCD_ 2存储在数据库中。基本方程式是今年(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();
}
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