簡體   English   中英

沒有在Codeigniter,MySQL中用LIKE搜索我想要的內容

[英]Not searching what I want with LIKE in Codeigniter, MySQL

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

先感謝您。

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子句意味着在要搜索的字符串的前面和后面添加% widcard,因此只要返回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在評論中說,你真的,真的要拆了這一點與teacherid和subjectid列的“teachersubject”表否則非常,非常快咬你的背部。 [去過也做過 :-) ]

例如,想象一下,試圖將以上內容擴展為尋找一位教書((數學或物理學)和英語)的老師。 惡夢!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM