PHP&找到了MySQL COUNT和ORDER BY结果

时间:2012-03-31 08:52:48

标签: php mysql codeigniter-2

我有这样的代码:

function search_keyword(){       

        $keyword = $this->db->escape_like_str(trim($_POST['keyword']));

        $sql = " ( SELECT  name, id_global_info AS id, body AS body, tag AS tag  ,info_type_id AS info_type, \"global_info\" AS mytable FROM global_info WHERE ";
         $sql .= " MATCH (name, body, tag) AGAINST ( '$keyword') ";
          $sql .= " ) UNION ALL "; 

          $sql .= " ( SELECT name, id_person AS id, surname AS body, info AS tag , location AS info_type, \"person\" AS mytable FROM person WHERE ";
             $sql .= " MATCH (name, surname, info) AGAINST ( '$keyword' ) ";       

          $sql .= " ) UNION ALL ";

          $sql .= "( SELECT name, id_event AS id, body AS body, caffe_id AS tag , date AS info_type, \"event\" AS mytable FROM event WHERE ";
             $sql .= " MATCH (name, body) AGAINST ( '$keyword' ) ";             

        $sql .= " ) UNION ALL ";

          $sql .= "( SELECT name, id_caffe AS id, description AS body, adress AS tag, location_id AS info_type, \"caffe\" AS mytable FROM caffe WHERE ";
             $sql .= " MATCH (name, description) AGAINST ( '$keyword' ) ";           

        $sql .= " ) ";        
        $q = $this->db->query($sql);
         return $q = $q->num_rows() == 0 ? FALSE :  $q->result();
    }

如何计算每行的结果数,然后按计数结果对它们进行排序?

实施例: 我想搜一车字 - 第一排有名车,而车身字车出现7次,而第二排车出现在车身上2次。我想计算找到汽车的时间,然后按计数结果订购结果。

1 个答案:

答案 0 :(得分:1)

我认为你最好用PHP做到这一点:

$counters = array();
foreach($q->result as $r)
  $counters[$r['mytable']]++;

由于我不知道你的数据库接口,这不是确切的代码,但我相信你可以得到一般的想法(我假设你的结果集对象是一个关联数组的数组)。

修改

备用架构

CREATE TABLE info_generic (id int not null auto_increment PRIMARY KEY, name varchar(100),
  record_type tinyint not null default 1, body TEXT, tag_id int , info_type_id int , 
  KEY (record_type) record_type,
  KEY(tag_id) tag_id,
  KEY(info_type_id) info_type_id
);

CREATE TABLE tags(id int not null auto_increment PRIMARY KEY,  description VARCHAR(100) );

CREATE TABLE info_types(id int not null auto_increment PRIMARY KEY, 
  description VARCHAR(100), record_type tinyint default 1 
);

属性解释

record_type:1 - > global_info,2 - >人,3 - >事件,4 - > CAFFE

body:1 - >身体,2 - >姓氏,3 - >身体,4 - >描述

标签:1 - >标签,2 - > info,3 - >身体,4 - >描述

然后,您可以使用INNER JOIN构建单个SQL,以将记录提供给Sphinx。