我需要知道如何使用MAX()
和COUNT()
查询来显示“ fiser”表条目,这些条目包含来自“ products”表的主“ codp”键,具体取决于以前选择的时期?
表产品: codp ,登普;
表订单: codc , codp ;
表返回值: codr ,datar, codc , codp
<?php
if(isset($_POST['add'])){
$sql = "SELECT p.denp, a.datar,MAX(p.codp)
FROM ( SELECT COUNT(p.codp) FROM products p ) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d') ";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if($queryResult > 0 ){
while ($row = mysqli_fetch_assoc($result)) {
echo "
<table border=1 >
<tr>
<td><p> ".$row['codp']." </p></td>
<td><p> ".$row['denp']." </p></td>
<td><p> " .$row['codr']." </p></td>
<td><p> " .$row['datar']." </p></td>
<td><p> " .$row['codc']." </p></td>
</tr> </table> ";
}
} else {
echo " No results!" ;
}
}
?>
答案 0 :(得分:1)
您应该将group by用于codp并加入相关结果,例如:
$sql = "SELECT p.denp, r.datar,MAX(p.cnt_codp)
FROM (
SELECT codp, COUNT(*) as cnt_codp FROM products
group by codp
) products p
INNER JOIN orders o ON p.codp=o.codp
INNER JOIN returns r ON o.codc=r.codc
WHERE r.datar>=STR_TO_DATE('".$_POST['d1']."','%Y-%m-%d')
AND r.datar<=STR_TO_DATE('".$_POST['d2']."','%Y-%m-%d')
GROUP BY p.denp, r.datar ";
,您应该检查数据库驱动程序以获取param bindig,而不要在sql中使用php var(您有进行sql注入的风险)
,并且还应该对未合并的列使用group by,或者如果需要与最大结果相关的值,请重新使用该问题(在SQL AI中最不推荐使用没有正确分组的列的聚集函数不允许使用最新版本的mysql)