I have a mails table which is my main tables for manipulating mails. I also have mails_sent and mails_dates which has FK connecting them with mails and contain data as follows mails_dates – a single mail could have more than one date set for sending so I have realtion 1:N where N are all the dates set from the user for the mail to be send and mails_sent – after a mail is sent a new record is added in this table with the id of the mail and the date it was sent. Because as I mentioned a mail could be sent more than once here the relation is also 1:N where N here represents the different dates when a mail was sent.
I need to show this info in a UI. First I had to show only the sending dates and I user this:
$this->db->select("mails.id, mails.subject, mails.dt_created, mails.groups");
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_dates.dt_sending_date, '%d-%m-%Y')) AS sending_dates", FALSE );
$this->db->join('mails_dates','mails_dates.mail_id = mails.id', 'left');
$this->db->join('mails_sent','mails_sent.mail_id = mails.id', 'left');
$this->db->from('mails');
$this->db->group_by('mails.id');
$res = $this->db->get()->result_array();
return $res;
When I was using this everything was fine I was getting a string with all the dates in it. But the problem is when I try to get the dates when a mail was sent. I added one more select:
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_sent.dt_sent, '%d-%m-%Y')) AS sent_dates", FALSE );
making my query looks like this:
$this->db->select("mails.id, mails.subject, mails.dt_created, mails.groups");
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_sent.dt_sent, '%d-%m-%Y')) AS sent_dates", FALSE );
$this->db->select("GROUP_CONCAT(DATE_FORMAT( mails_dates.dt_sending_date, '%d-%m-%Y')) AS sending_dates", FALSE );
$this->db->join('mails_dates','mails_dates.mail_id = mails.id', 'left');
$this->db->join('mails_sent','mails_sent.mail_id = mails.id', 'left');
$this->db->from('mails');
$this->db->group_by('mails.id');
$res = $this->db->get()->result_array();
return $res;
But the problem is that If sending_dates contains let’s say – 6 values, and sent_dates has only one I end up with a string containing 6 times the value of sent_dates. This is in production so I don’t have a lot of records but the same happens with a query where I have 2 sending_dates and 1 record for sent_dates still I get 2 times the record from sent_dates.
How can I fix this?
Thanks
Leron
Ok, I found the solution, here it is:
In other words just use
DISTINCT.