问题
I have one problem while retrieveing value from mysql using codeigniter.
I have one table name task and in that there is one field of assigneduserid.
Table - Task:
id | title | assigneduserid
-------------------------------------
1 | Workspace | 23,21
Table - User
id | title
-----------------
23 | Ashish
21 | Ritesh
In assigneduserid field there are two values in that field that is 23,21.
I want to print both usertitle like this : Ashish,Ritesh from usertable using that assigneduserid.
And also i want to set that value in ascending order which are in assigneduseid
I am trying to print that record on page using echo like following
Following is Code Where i am printing:
<?php echo $task_row->usertitle;?>
Above code is printing only Ashish.
but i would like to print Ashish,Ritesh
following is my model.
function getTask($id, $is_master_admin)
{
$this->db->select('workspace.title as workspacetitle, user.title as usertitle,task.*');
$this->db->join(WORKSPACE, WORKSPACE . '.id = ' . TASK . '.workspaceid', 'inner');
$this->db->join(USER, USER . '.id = ' . TASK . '.assigneduserid', 'inner');
$this->db->from(TASK);
if (!$is_master_admin) {
$this->db->where(USER . '.id', $id);
}
$this->db->where(TASK . '.tasktypeid', '1');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
Thank you in advanced
回答1:
use this
function getTask($id, $is_master_admin)
{
$this->db->select('task.*, workspace.title as workspacetitle, GROUP_CONCAT( user.title ) AS usertitle,task.assigneduserid,user.id',FALSE);
$this->db->join(WORKSPACE , WORKSPACE . '.id = ' . TASK . '.workspaceid', 'inner');
$this->db->join(USER,("FIND_IN_SET(USER .id , TASK.assigneduserid)"), 'inner');
$this->db->from(TASK);
$this->db->group_by("task.id");
if (!$is_master_admin)
{
$this->db->where ("FIND_IN_SET($id, task.assigneduserid)");
}
$this->db->where(TASK . '.tasktypeid', '1');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return false;
}
}
回答2:
Use FIND_IN_SET() & GROUP_CONCAT() functions
Try this:
SELECT t.id, t.title, GROUP_CONCAT(u.title) AS userTitle
FROM Task t
INNER JOIN User u ON FIND_IN_SET(t.assigneduserid, u.id)
GROUP BY t.id
EDIT::
SELECT t.id, t.title, GROUP_CONCAT(u.title) AS userTitle
FROM Task t
INNER JOIN `User` u ON CONCAT(',', t.assigneduserid, ',') LIKE ('%,', u.id, ',%')
GROUP BY t.id
回答3:
@Ritesh: follow Saharsh Shah, you can put this query into this command $this->db->query(); or you can follow this link to do what you want http://ellislab.com/codeigniter/user-guide/database/active_record.html
来源:https://stackoverflow.com/questions/20878315/retrieve-and-print-values-after-comma-separator-from-single-field-using-join-co