php - 在 MySql 数据库中存储、检索和搜索标签

标签 php mysql

我将产品存储在带有标签的 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。我目前正在使用下面的方法,但这只检查唯一行,而不检查唯一标签(逗号分隔值),所以我得到了重复值。

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

如何获得唯一标签列表?以及如何在标签中搜索多个值? (所以如果我搜索“nice yellow”,它会返回奶酪。

最佳答案

使用具有给定结构的单个查询获取唯一标签并不简单。按照其他人的建议,最好的做法是规范化数据,这将有助于许多操作,例如搜索、获取唯一数据等。

现在对于第一个问题这里是获取它的一种方法

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 中拆分字符串,然后使用 like with AND 以确保您正在搜索的所有标签都在结果中返回。

使用规范化的表结构,这会容易得多。

关于php - 在 MySql 数据库中存储、检索和搜索标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21509100/

相关文章:

php - 从 MySQL 中仅最新创建的数据集记录中选择所有字段?

php - MySql错误: Result consisted of more than one row

PHP 将语义版本控制字符串转换为整数/ float

php - 寻求一种有效的方法来查找哪些行已受到 mysql 更新操作的影响

mysql - 如果没有结果,选择 COUNT (*) 失败

MySQL:根据多个条件从多个列中选择数据

javascript - 查找 JavaScript 错误代码列表

用于限制的 php bind_param

php - Sweet Alert 2 - "confirmButtonText"按钮中的链接

mysql - 当名称略有不同时按名称合并 mysql 行