PHP problem with JOIN statement in CodeIgniter
I have two tables: 'events_archive' and 'demo_users'. In the events table, each event has a unique ref_id
value, a demo_id
value (the user ID of the demonstrator w开发者_如何学JAVAho participated in the event) and a client_id
value (the user ID of the client who participated in the event). In the demos table, each demonstrator has a unique id
value that corresponds to the demo_id
in the events table.
What I want to do is list all demonstrators (from the demos table) that participated in events that a particular client did. I'm getting the particular client's user ID with session data.
So say the client_id
value is 4, I want to list all the individual demonstrators that have shared an event (i.e. shared a row in the table). I'm currently using this in my CodeIgniter model:
function demos($mid){
$this->db->select('demo_users.*');
$this->db->from('demo_users');
$this->db->join('events_archive','events_archive.demo_id = demo_users.id');
$this->db->where('events_archive.client_id',$mid);
$this->db->limit(10);
$this->db->order_by('users_demonstrators.products_sold','asc');
$demos = $this->db->get();
foreach($demos->result() as $demo){
echo $demo->first_name;
}
}
But instead of listing the demonstrators individually, it duplicates them over and over. Instead of listing Demonstrator A, Demonstrator D, Demonstrator F, etc. it lists Demonstrator A, Demonstrator A, Demonstrator A, etc. Does anybody know where I'm going wrong?
Instead of $this->db->select('demo_users.*')
try $this->db->select('*')
and instead of echo $demo->first_name;
try var_dump($demo);
.
My guess is that Demonstrator A
has many records in events_archive
. You join the two tables and as a result, each matching record in events_archive
gets added with the columns from demo_users
. That's why you get multiple demo_users.*
- but the records have different events_archive.*
values.
You maybe want to try SELECT DISTINCT.
精彩评论