php - 不同的 mysql 结果 - codeigniter

标签 php mysql codeigniter

我正在使用两个表来保存有关汽车的信息。在第一个表中有关于汽车制造商等的信息,第二个包含每辆车的图像。我的表格如下所示:

car_information    car_images
---------------    ---------
id       | 2       car_id 2 | img1
car_make | Fiat    car_id 2 | img2
color    | Blue    car_id 2 | img3
etc ....

如您所见,每辆车都有三张图片。

这是我用来获取结果的查询;

 $this->db->select('
           c.id,
           c.car_make,
           c.car_color,
           ci.image
        ');       

  $this->db->from('car_information c');
  $this->db->join('car_images ci', 'ci.car_id = c.id', 'left');
  return $this->db->get();  

一切正常,但我面临的问题是结果重复。

例如:

2 Fiat Blue img1
2 Fiat Blue img2
2 Fiat Blue img3

3 BMW white img4
3 BMW white img5

怎么做才能让结果看起来像这样

2 Fiat Blue img1 | img 2 | img 3

我想在单行中获取所有信息。 我知道我可以为您提供两个查询,但我想知道如何处理单个查询?

最佳答案

添加以下行:$this->db->group_by('c.id');

像这样:

 $this->db->select('
           c.id,
           c.car_make,
           c.car_color,
           ci.image
        ');       

  $this->db->from('car_information c');
  $this->db->join('car_images ci', 'ci.car_id = c.id', 'left');
  $this->db->group_by('c.id');
  return $this->db->get();  

这将在 MySQL 中起作用,因为 group by 在 MySQL 中可以用作 distinct 的同义词。

关于php - 不同的 mysql 结果 - codeigniter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5927437/

相关文章:

php - Symfony2如何使用验证器组件验证唯一的电子邮件

php - Mysql使用IN搜索包含每个IN子句单词的条目

mysql - 将相似的值分组到新的 select 语句中

mysql - 带条件选择的子查询

php - 尝试将图像上传到 mysql 数据库时无法执行 PDO 查询

php - 如果嵌套数组为空,则删除 mongo 数组

mysql:如何避免两次保存相同的数据?

mysql - 如何插入值(codeigniter)

jquery - Ignited-Datatables,应该怎么做?

php - CodeIgniter anchor 错误: URL not found on this server