我在be_user_profiles.subject中有以下示例。这些是每个老师教的科目编号。
1// English
1,2 // English and Math etc
1,2,14
2,4,114
12,24,34
15, 23
我想选择be_user_profiles。受试者有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();
提前感谢。
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'
");
您放入like
查询中的both
子句意味着在要搜索的字符串的前面和后面添加%
通配符,因此只要12、21、121等,它就返回1。如果你删除它,它将只搜索精确匹配。
你可以添加这个like
子句,并添加逗号到它,我认为它会工作。试着添加这个,而不是你现在的like
:
$this->db->like("," . "be_users.group" . "," , "," . $subjectid. "," , both);
我想你可以在这里使用正则表达式模式。
$pattern = "(^|.*,)1(,.*|$)";
...
...
$this->db->select('*');
....etc
$this->db->where("be_user_profiles.subject REGEXP $pattern");
此正则表达式模式假定逗号字符串中没有空格。
然而,正如@halfer在评论中所说的,你真的,真的应该把它分割成一个"teachersubject"表,其中包含teacherid和subjectid列,否则它将会很快在背后咬你。[亲身经历过:-)]
想象一下,试着把上面的问题扩展到寻找一个教(数学或物理)和英语的老师。噩梦!