1

我一直在尝试制作一个程序,该程序将从我的数据库中读取所有列,并且如果这些列具有相同的年龄出现不止一次(例如,如果两行的年龄相同 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 岁。从最后两个中,只有一个出现在屏幕上)。

提前致谢。

4

3 回答 3

3

GROUP BY折叠你的点击。您可以这样解决问题:

SELECT * FROM table2 WHERE Age IN 
(SELECT Age from table2 GROUP BY Age HAVING (COUNT(Age) > 1))
于 2013-09-13T05:16:13.523 回答
1

您也可以使用子查询

SELECT table2.* FROM table2 
JOIN
(SELECT age FROM table2 GROUP BY Age HAVING (COUNT(Age) > 1)) AS temp 
ON temp.age=table2.age
于 2013-09-13T05:21:02.090 回答
0
SELECT Surname  
FROM table2 
GROUP BY Name 
group by Age 
HAVING (COUNT(Age) > 1)
于 2013-09-13T05:28:42.613 回答