2013-03-20 20 views
0

我在be_user_profiles.subject中有下面的例子。這些都是每個教師教授的主題ID。在Codeigniter中沒有用LIKE來搜索我想要的,MySQL

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(); 

在此先感謝您。

+0

這些逗號分隔的字符串實際上是否存儲在您的表中?如果是這樣,將它分離到另一個表中,並將它們存儲爲整數 - 這種方法很快就會遇到連接問題。 – halfer 2013-03-20 08:31:55

+0

在此完全同意halfer,請先修復您的數據。這幾乎違背了關係數據庫的概念。您需要一個存儲教師ID和主題ID的連接表,然後對其進行連接。 – 2013-03-20 12:08:13

回答

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

,你投入like查詢的both條款是指在前面加% widcard和後字符串進行搜索,所以它返回1,只要12,21,121等。如果刪除它,它將只搜索完全匹配。

您可以添加此like子句並向它添加逗號,我認爲它會起作用。嘗試添加的,而不是like這個你現在有:

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

我認爲你可以在這裏使用正則表達式模式。

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

此正則表達式模式假定逗號字符串中沒有空格。

然而,正如@halfer在評論中所說的那樣,真的應該把它分成一個「tentsrid」和tejeerid列的「teachersubject」表,否則它很快就會在背後咬你。 [在那裏,做到這一點:-)]

eg想象一下,試圖擴大到尋找教((數學或物理)和英語)的老師。惡夢!