如何使用codeigniter对相同的mysql表值进行排序?

时间:2013-05-08 04:41:03

标签: php mysql codeigniter

我想要做的是使用codeigniter从mysql中选择并对值进行排序

我的数据库记录:

Criteria | Question
   A     |    Q1
   B     |    Q2
   c     |    Q3
   A     |    Q4
   A     |    Q5

我想在界面中显示的内容:

A
--------
Q1
Q4
Q5

B
--------
Q2

C
--------
Q3

这就是我的代码的样子

$this->db->select('*');
$this->db->from('qm_form');
$this->db->join('criteria', 'qm_form.criteria_id = criteria.criteria_id');
$this->db->join('question', 'criteria.criteria_id = question.criteria_id');
$this->db->group_by('criteria_title');
$this->db->order_by('criteria_title','asc','question_title','asc');
$query = $this->db->get();

return $query->result();

MYSQL TABLE
question table
question_id | criteria_id | question_title

criteria_table
criteria_id | criteria_title

qm_form table
qm_id | criteria_id | qm_title 

任何想法怎么做?

感谢

3 个答案:

答案 0 :(得分:1)

尝试使用group by

$this->db->select('*');
$this->db->from('my_table');
$this->db->group_by('Question');
$this->db->order_by('Critera','asc');
$query = $this->db->get();
$result = $query->result();

然后打印

foreach($result as $element)
{
    $hash = $element['Critera'];
    $unique_array[$hash] = $element
}

答案 1 :(得分:1)

您可以使用两个命令来执行此操作:

$this->db->select('*');
$this->db->from('my_table');
$this->db->order_by("Criteria", "asc");
$this->db->order_by("Question", "asc"); 
$query = $this->db->get();
$result = $query->result(); 

答案 2 :(得分:1)

恕我直言,你只需要相当于一个查询

SELECT *
  FROM tablename
ORDER BY `Criteria`, `Question`

<强> SQLFiddle

我不是CodeIgniter的专家,但您可以尝试

$this->db->select('*');
$this->db->from('tablename');
$this->db->order_by('Criteria ASC, Question ASC');
...

更新:根据您的评论,您需要等效的查询

SELECT `Criteria`, GROUP_CONCAT(`Question`)
  FROM tablename
GROUP BY `Criteria`
ORDER BY `Criteria` 

<强> SQLFiddle

这可能转化为

$this->db->select('Criteria, GROUP_CONCAT(Question)');
$this->db->from('tablename');
$this->db->group_by('Criteria');
$this->db->order_by('Criteria', 'asc');
...

假设您的联接正确,请尝试

$this->db->select('criteria.criteria_title, GROUP_CONCAT(question.question_title)');
$this->db->from('qm_form');
$this->db->join('criteria', 'qm_form.criteria_id = criteria.criteria_id');
$this->db->join('question', 'criteria.criteria_id = question.criteria_id');
$this->db->group_by('criteria.criteria_title');
$this->db->order_by('criteria.criteria_title', 'asc');