每天相同值的数量

时间:2017-07-10 13:58:59

标签: php sql count

我是否需要建议如何从数据库中计算指定日期的指定数量的值?

在数据库中我有这个:

title      cas     datum
Karel      9-14    2017-07-06
Petr       9-14    2017-07-06
Kuba       14-19   2017-07-06
Ivo        9-14    2017-07-04

结果是计算它的次数。例子9-14在2017-07-06答案:2

我尝试了这样,但它列出了表格中的所有值以及另一个日期。

$cas = '14-19';
$result = $db->query("SELECT Count(datum) as r FROM events WHERE cas = '".$cas."'");
$row = $result->fetch_assoc();
echo $row['r'];

2 个答案:

答案 0 :(得分:1)

只需将日期条件添加到您的sql

即可

注意SQL语句中的AND datum = ?

$cas = "9-14";
$datum = "2017-07-06";

$mysqli = new mysqli("example.com", "user", "password", "database");

$query = "SELECT COUNT(datum) AS r FROM events WHERE cas = ? AND datum = ?";
$stmt = $mysqli->prepare($query);
!$stmt ? die('error') : "";
$stmt->bind_param('ss', $cas, $datum);
$stmt->execute();
$row = $stmt->get_result()->fetch_array(MYSQLI_ASSOC);
echo $row['r'];
exit;

答案 1 :(得分:0)

1)您没有将datum放在WHERE子句中。这可能就是为什么它会向你展示另一个约会。

$cas = '14-19';
$datum = '2017-07-06'; 
result = $db->query("SELECT Count(datum) as r FROM events WHERE cas = '".$cas."' AND datum = '".$datum."'");

2)您是否要指定datumcas?如果没有,请查看GROUP BY子句。

result = $db->query("SELECT datum, cas, Count(*) as r FROM events GROUP BY datum, cas");