如何删除表中的重复行

时间:2019-04-09 07:22:14

标签: php mysql sql codeigniter

我是Codeigniter框架工作的新成员,我正在尝试停止表中的重复记录 在我的表记录中重复,我想一次显示一个记录

这是我的代码

控制器

  $modelResult = $this->freightBillModel->freightBillByDate($data);
  <table id="freight_table" class="table table-bordered table-striped table-sm" style="display:block; overflow: auto; ">
             <tr>
              <th>SR.No</th>
              <th>Bill No</th>
              <th>pkgs</th>
              <th>freight</th>
             </tr>
             <tbody>
                <?php  $counter = 1;   ?>
                <?php foreach($modelResult as $freight){?>

            <tr>

              <td><?php echo $counter;?></td>
              <td><?php echo $freight['tbb_no'];?></td>
              <?php $singleBill = $this->freightBillModel->fetchBillByNo($freight['tbb_no']);  ?>
              <?php $lr_freight=0; $no_of_pkgs=0; ?>

              <?php foreach ($singleBill as $bill) : ?>
              <?php $lr_freight+=$bill->lr_freight; ?>
              <?php $no_of_pkgs+=$bill->no_of_pkgs; ?>
              <?php endforeach; ?>

              <td><?php echo $no_of_pkgs;?></td>
              <td><?php echo $lr_freight;?></td>


             </tr>
            <?php  $counter++; ?>
            <?php }?>
            </tbody>
          </table>

型号:

        public function freightBillByDate($data){
        extract($data);
        $this->db->select('bn.branch_name as to,ts_tbb.tbb_no,ts_tbb.tbb_id,ts_tbb.bilty_id,ts_tbb.current_time,ts_tbb.status,b.*');
        $this->db->from('ts_tbb');
        $this->db->join('bilty b', 'b.id = ts_tbb.bilty_id');

        $this->db->join('branch bn', 'b.lr_to=bn.branch_id');

        $this->db->where('lr_from',$lr_from);
        $this->db->where('lr_to',$lr_to);


        if($bill_type=="pending_bill"){

               $this->db->where('billed_status','not_billed');

         }else if($bill_type=="bill_register"){

               $this->db->where('billed_status','billed');
         }




        $this->db->order_by('lr_date','desc');


        $query=$this->db->get();
       return $query->result_array();

}
function fetchBillByNo($billNo){
    return $this->db->select('*')->from('ts_tbb')->join('bilty','bilty_id=bilty.id')->where('tbb_no',$billNo)->get()->result();
}[![In this picture first two records are repeat][1]][1]

我想显示唯一记录, 当前表显示重复的行 请告诉我我的代码在哪里错了

3 个答案:

答案 0 :(得分:3)

如果要查询不同的行,只需使用SELECT DISTINCT而不是SELECT。

答案 1 :(得分:1)

您可以在DISTINCT中添加select()关键字

return $this->db
->select('DISTINCT YOUR_ID_FIELD')
->select('*')
->from('ts_tbb')
->join('bilty','bilty_id=bilty.id')
->where('tbb_no',$billNo)
->get()
->result();

否则,您可以像这样使用group by

$this->db->select('*');
$this->db->group_by('YOUR_ID_FIELD');

答案 2 :(得分:1)

保留重复记录不是一个好习惯,您可以删除SQL查询中所有重复的记录。

例如:

DELETE t1 FROM contacts t1
INNER JOIN
contacts t2 
WHERE
t1.id < t2.id AND t1.email = t2.email;

以上SQL查询将删除重复的电子邮件行,并保留最高ID。

相关问题