使用codeigniter的Mysql Pivot表

时间:2018-03-09 16:59:07

标签: mysql codeigniter pivot-table

我需要在codeigniter中生成像数据透视表这样的报告。它在mysql PHPmyadmin中工作但是当我在codeigniter中使用它时会显示sql语法错误。

Error Number: 1064

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
SET @sql = CONCAT('SELECT sf.nc_name, sf.code, ', @sql, 'FROM sirform AS sf INNER JOIN rejection AS rb ON sf.id = rb.sir_id GROUP BY sf.nc_name'

Filename: C:\xampp\htdocs\rnaiplpqcms\system\database\DB_driver.php

Line Number: 331

 //Controller
 public function report(){
    $data['report'] = $this->user_model->report(); 
    $this->load->view("templates/header");
    $this->load->view("pivot_report",$data);
    $this->load->view("templates/footer");
  }
  
  //Model
  
   public function report(){
        $this->db->query("SET @sql = NULL");
        $this->db->query("SELECT GROUP_CONCAT(DISTINCT CONCAT('MAX(IF(rb.model = ''',model,''', rb.quantity, NULL)) AS ',model)) INTO @sql FROM rejection");
        $this->db->query("SET @sql = CONCAT('SELECT sf.nc_name, sf.code, ', @sql, 'FROM sirform AS sf INNER JOIN rejection AS rb ON sf.id = rb.sir_id GROUP BY sf.nc_name'");
          $this->db->query("PREPARE stmt FROM @sql");
        $this->db->query("EXECUTE stmt");
        $this->db->query("DEALLOCATE PREPARE stmt");        
		
        $query = $this->db->get();
        return $query->result_array();
      }
	  
	  //View
	 <table id="example1" class="table table-bordered table-striped table1">
            <thead>
               <tr>
                 <th>Code</th>
                 <th>Name</th>
                 <th>Quantity</th>
                 <th>Model</th>
               </tr>
             </thead>
             <tbody>
              <?php if(isset($report)) {
                foreach($report  as $reports){ ?>
               <tr>
                 <td><?php echo $reports['code']; ?></td>
                 <td><?php echo $reports['name']; ?></td>
                 <td><?php echo $reports['quantity']; ?></td>
                 <td><?php echo $reports['model']; ?></td>// Model as header and quantity below it
                </tr>
                <?php }} ?>
              </tbody>
            </table>

<!--Expected Output-->
<table border=1>
<tr>
  <th>Code</th>
  <th>Name</th>
  <th>Model1</th><!--Model Column as header-->
  <th>Model2</th>
  <th>Model3</th>
</tr>
<tr>
  <td>123</td>
  <td>xyz</td>
  <td>2</td>
  <td>0</td>
  <td>2</td>
</tr>
<tr>
  <td>456</td>
  <td>abc</td>
  <td>5</td>
  <td>3</td>
  <td>0</td>
</tr>
</table>

2 个答案:

答案 0 :(得分:1)

为什么不将查询转换为mysql上的存储过程并从codeigniter执行SP?

答案 1 :(得分:0)

您没有关闭CONCAT方法的括号。

$this->db->query("SET @sql = CONCAT('SELECT sf.nc_name, sf.code, ', @sql, 'FROM sirform AS sf INNER JOIN rejection AS rb ON sf.id = rb.sir_id GROUP BY sf.nc_name')");