簡體   English   中英

在MySql數據庫中存儲,檢索和搜索標簽

[英]Storing, retrieving and searching tags in MySql Database

我將產品存儲在帶有標簽的mysql數據庫中(現在已用逗號分隔):

name       |   price   | tags
-----------------------------------------
cheese     |   6       | yellow, nice
strawberry |   3       | red, fruit
steak      |   5       | red, nice feeling, cold
rice       |   4       | white, china

現在,我想獲得一個唯一標簽的列表,該標簽應該返回yellow, nice, red, fruit, nice feeling, cold, white, china 我當前正在使用下面的方法,但這只會檢查唯一的行,而不是唯一的標記(逗號分隔的值),因此Im會得到重復的值。

      $result = mysql_query("SELECT DISTINCT tags FROM products") or die(mysql_error());

      // check for empty result
      if (mysql_num_rows($result) > 0) {
      // looping through all results
      // products node
      while($row = mysql_fetch_array( $result )) {               
            // echo out the contents of each row into a table
            if  (!empty($row["tags"])){
            echo  "The tags are: ".$row["tags"] ;
            }
       } 

另外,我想搜索數據庫,我已經可以工作了:

       $ref = $tags;
       $query = "SELECT * FROM products WHERE INSTR(tags,'".mysql_real_escape_string($ref)."')>'0'";
       $result = mysql_query($query);

如何獲得唯一標簽列表? 以及如何在標簽中搜索多個值? (因此,如果我搜索“漂亮的黃色”,它將返回奶酪。

使用具有給定結構的單個查詢來獲取唯一標簽並不簡單。 最好的做法是按照他人的建議對數據進行標准化,這將有助於許多操作,例如搜索,獲取唯一數據等。

現在第一個問題是獲得它的一種方法

select distinct reverse(substring_index(reverse(substring_index(tags, ',', n.n)), ',', 1)) as tags
from products cross join
     (select 1 as n union all select 2 as n union all select 3 as n union all select 4 as n) n
having tags is not null

在此處查看輸出http://www.sqlfiddle.com/#!2/d9a42/18

現在,對於字符串模式來說,直接進行搜索是一個大問題,因此您可能需要在PHP中拆分字符串,然后將其與AND一起使用,以確保所搜索的所有標簽均返回結果。

使用規范化的表結構,這將更加容易。

您應該閱讀有關數據規范化的信息。 本質上,您應該單獨存儲標簽。 這樣,每個標簽都會有一個ID,每個產品都會有一個ID。 產品和標簽之間存在許多關系,這意味着您將擁有一個將標簽鏈接到產品的表格。

您應該閱讀以下問題: 在數據庫列中存儲分隔列表真的那么糟糕嗎?

暫無
暫無

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

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