【问题标题】:Want to output from 2 tables with same column name. Using codeigniter想要从具有相同列名的 2 个表中输出。使用代码点火器
【发布时间】:2017-05-18 16:11:53
【问题描述】:

我有 2 个不同的表,具有相同的列名 tbl_specialty 和 tbl_student。我做了一个 JOIN 语句来加入 2 个表,现在我想输出表 1 的列名和表 2 的列名,我该如何实现呢?我只从一列复制。 请帮忙。

我的观点

 <?php
       foreach ($delegates->result() as $row )  
 {?>
       <tr>
          <td><a href=""> <?php echo $row->name; ?></a></td>
          <td class="center"><?php echo $row->job; ?></td>
          <td class="center"><?php echo $row->name; ?></td>
          <td class="center"><?php echo $row->workplace;?></td>
          <td class="center"><?php echo $row->country_name; ?></td>
      </tr>                   

我的模型

public function delegates_per_course()  {  
  $this>db>select('tbl_student.name,tbl_student.workplace,tbl_student.job,tbl_student.dob,tbl_student.email,tbl_student.mobile,tbl_country.country_name,tbl_specialty.name,tbl_country.country_id,tbl_country.country_name');
  $this->db->from('tbl_student');
  $this->db->join('tbl_country','tbl_student.country_id=tbl_country.country_id'); 
  $this->db->join('tbl_specialty','tbl_student.specialty_id=tbl_specialty.id'); 
  $this->db->order_by("tbl_country.country_name");
  $query = $this->db->get();
  return $query; 

}

【问题讨论】:

    标签: mysql codeigniter codeigniter-2 codeigniter-3


    【解决方案1】:

    来自http://www.w3schools.com/sql/sql_union.asp

    块引用 UNION 运算符用于组合两个或多个 SELECT 语句的结果集。注意 UNION 中的每个 SELECT 语句必须具有相同数量的列。这些列还必须具有相似的数据类型。此外,每个 SELECT 语句中的列的顺序必须相同。

    在你的情况下,它看起来像这样:

    SELECT columnname FROM tbl_specialty
    UNION ALL
    SELECT columnname FROM tbl_student;
    

    【讨论】:

      【解决方案2】:

      试试这个:

      $this->db->select('tbl_student.name as stud_name,tbl_student.workplace,tbl_student.job,tbl_student.dob,tbl_student.email,tbl_student.mobile,tbl_country.country_name,tbl_specialty.name as spec_name,tbl_country.country_id,tbl_country.country_name');
      

      我已更改查询并为同名列创建别名,例如:

      tbl_student.name as stud_name
      tbl_specialty.name as spec_name
      

      现在您可以通过使用别名来正确引用它们。在没有别名的情况下,tbl_specialty.name 会覆盖 tbl_student.name

      的值

      【讨论】:

      • 嘿。谢谢回复。我将如何在我的视图中输出它。而不是 foreach ($delegates -> result () as $row ) 我写什么?
      • 同理,使用$row->stud_name;和 $row->spec_name;引用这两列
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-05
      • 1970-01-01
      • 2013-04-19
      • 2010-09-16
      • 1970-01-01
      相关资源
      最近更新 更多