在Codeigniter,MySQL中没有用LIKE搜索我想要的东西

时间:2013-03-20 08:09:11

标签: php mysql codeigniter

我在be_user_profiles.subject中有以下示例。这些是每位老师教授的主题ID。

1// English
1,2 // English and Math etc
1,2,14
2,4,114
12,24,34
15, 23

我想选择be_user_profiles.subject所具有的位置1.当我使用以下内容时,它会输出其中包含1的所有内容。所以它将输出所有。我试过HAVING,但它只选择完全匹配。所以它只显示第一个。如何获取具有be_user_profiles.subject?

的数据
    $this->db->select('*');
    $this->db->from('be_user_profiles');
    $this->db->join('be_users', 'be_users.id = be_user_profiles.user_id');
    $this->db->where('be_users.group', $teachergrp);
    $this->db->like('be_user_profiles.subject', $subjectid);
    //$this->db->having("be_user_profiles.subject = $subjectid");// this picks up only exact match 
    $query = $this->db->get();

提前谢谢。

3 个答案:

答案 0 :(得分:3)

be_user_profiles表

row1: 1,2,14

row2: 2,4,114

row3: 12,24,34

row4: 15, 23

要获得完全匹配的数据,请使用此查询

$this->db->query("
      SELECT * FROM `be_user_profiles` 
      WHERE subject LIKE '1'

      UNION

      SELECT * FROM `be_user_profiles` 
      WHERE subject LIKE '1,%'

      UNION

      SELECT * FROM `be_user_profiles` 
      WHERE subject LIKE '%,1,%'

      UNION

      SELECT * FROM `be_user_profiles` 
      WHERE subject LIKE '%,1'

   ");

答案 1 :(得分:1)

您在both查询中添加的like子句意味着在搜索字符串的前面和后面添加% widcard,因此它返回1只要12,21 ,121等。如果你删除它,它将只搜索完全匹配。

您可以添加此like子句并为其添加逗号,我认为它会起作用。尝试添加此项而不是现在的like

$this->db->like("," . "be_users.group" . "," , "," . $subjectid. "," , both);

答案 2 :(得分:0)

我认为你可以在这里使用正则表达式。

$pattern = "(^|.*,)1(,.*|$)";
...
...
$this->db->select('*');
....etc
$this->db->where("be_user_profiles.subject REGEXP $pattern");

此正则表达式模式假定逗号字符串中没有空格。

然而,正如@halfer在评论中所说,你真的应该把它拆分成一个带有teacherid和subjectid专栏的“教师主题”表,否则很快就会在背后咬你。 [去过那里,完成了:-)]

例如,想象一下,尝试将上述内容扩展到寻找教授((数学或物理)和英语)的老师。恶梦!