没有显示所有结果

时间:2013-09-13 05:10:30

标签: php sql

我一直在尝试制作一个程序,它将从我的数据库读取所有列,如果这些列具有相同的年龄,则会出现多次(例如,如果两行具有相同的年龄15,则应显示这两行)

这是我试图制作的代码:

include('dbcon_3.php');  

if ( $mysqli->connect_errno ) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit();
}

$sql = "SELECT * FROM table2 GROUP BY Age HAVING ( COUNT( Age ) > 1 )";
$result = $mysqli->query( $sql );
if ( $result->num_rows > 0 ) {
  while ( $row = $result->fetch_row() ) {
     for ( $j = 0; $j <= count( $row ) - 1; $j++ ) {
        echo  $row[$j];
     }
  }
} else if ( $result->num_rows == 0 ) {
   echo "Not found";
}

此代码的结果只是应该出现的行之一(我已经测试了三行,一个是16岁,两个是15岁。从最后两个只有一个出现在屏幕上)。

提前致谢。

3 个答案:

答案 0 :(得分:3)

GROUP BY崩溃你的命中。你可以解决这个问题:

SELECT * FROM table2 WHERE Age IN 
(SELECT Age from table2 GROUP BY Age HAVING (COUNT(Age) > 1))

答案 1 :(得分:1)

您也可以使用子查询

SELECT table2.* FROM table2 
JOIN
(SELECT age FROM table2 GROUP BY Age HAVING (COUNT(Age) > 1)) AS temp 
ON temp.age=table2.age

答案 2 :(得分:0)

SELECT Surname  
FROM table2 
GROUP BY Name 
group by Age 
HAVING (COUNT(Age) > 1)