开发者

Distinct mysql result - codeigniter

I`m using two tables to hold information about cars. In the first table there is a information about car manufacturer etc and the second contain images for each car. My tables looks like this:

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

As you can see each car has three images.

Here is query i`m using to fetch the result;

 $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();  

Everything works fine but the problems i`m facing is that results are duplicated.

For example:

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

3 BMW white img4
3 BMW white img5

What to do so the result to looks like this

2 Fiat Blue img1 | img 2 | img 3

I want to get 开发者_开发百科all information in single row. I know that I can you two queries, but I`m wondering how to do with a single ?


Add the following line: $this->db->group_by('c.id');

like so:

 $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();  

This will work in MySQL because group by can be used as a synonym for distinct in MySQL.


Your joining 2 tables so you would get the same results from car_information if there are multiple images! You have to do this as 2 queries or just use the first result array to extract the car info then loop over it and just use the image data.


I think here's the answer you're looking for. http://codeigniter.com/forums/viewthread/100523/ Also read the codeigniter user_guide here http://codeigniter.com/user_guide/database/active_record.html

Your query is correct but SQL doesn't work like that. You get the raw data you asked, formatting must be done in your programming language (php in this case) as far as i know.

$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');
$query = $this->db->get();  

$i = 1;
foreach ($query->result() as $row) {
 $car_array[$row->car_id][$i++] = $row->image;
}
var_dump($car_array);

that will create an array that will contain all images for a car_id

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜