0

我想做的是使用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 

知道怎么做吗?

谢谢

4

3 回答 3

1

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

$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(); 
于 2013-05-08T04:51:39.867 回答
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');
于 2013-05-08T04:52:04.133 回答
1

尝试按赞分组

$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
}
于 2013-05-08T04:45:22.757 回答