php - 使用 PHP 和 MySQL 从数据库获取数据时无法避免重复数据

标签 php mysql

我有一个问题。使用 PHP 和 MySQL 从数据库检索时,我无法避免重复数据。我在下面解释我的代码。

   <?php
require_once '../../include/dbconfig.php'; 
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$colg_id=$request->colg_id;
$result = mysqli_query($connect, "SELECT DISTINCT dept_id  from db_unit_plan where clg_id='".$colg_id."'  ");
if($row =mysqli_fetch_assoc($result)) {
    //$dept_id = $row[dept_id]; 
    //$result = mysqli_query($connect, "select *  from db_department where colg_id='".$colg_id."' and dept_id='".$dept_id."'  ");
    $data = array();
    while ($row =mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }

print json_encode($data);
}
?>

db_unit_plan表中,许多行具有相同的dept_id。这里我需要避免重复的数据。请帮助我。

最佳答案

<?php
require_once '../../include/dbconfig.php'; 
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$colg_id=$request->colg_id;
$result = mysqli_query($connect, "SELECT DISTINCT dept_id FROM db_unit_plan where clg_id='".$colg_id."'  ");

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row['dept_id'];
}

print json_encode($data);

编辑

如果您需要结果中唯一的 db_department 列表:

<?php
require_once '../../include/dbconfig.php'; 
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$colg_id=$request->colg_id;
$result = mysqli_query($connect, "SELECT DISTINCT db_department.*  
    FROM db_department 
    JOIN db_unit_plan ON db_unit_plan.dept_id = db_department.dept_id
    WHERE db_unit_plan.clg_id='".$colg_id."'  ");

$data = array();
while ($row = mysqli_fetch_assoc($result)) {
    $data[] = $row;
}

print json_encode($data);

关于php - 使用 PHP 和 MySQL 从数据库获取数据时无法避免重复数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33968315/

相关文章:

mysql - 左连接是否可以表示为右连接,反之亦然?

mysql - 获取 MySQL 中分层类别的所有父级

php - 为什么运行 Laravel/Doctrine 原始数据库查询与使用 mysql cli 不同?

php - 交响乐 4 : An error occurred while loading the web debug toolbar

php - 转换表ascii php中的特殊字符

php - Xpath 查询查找其后代包含特定文本的节点

mysql - 创建mysql触发器时出错

Javascript/Jquery - 如何根据变量设置变量名

php - 合并两个 MySQL 表但希望一列等于另一列

mysql - 无法(重新)为 debian-sys-maint 设置权限,错误 1045 访问被拒绝