Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/joomla/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 基于标记的数据库查询_Php_Mysql_Database - Fatal编程技术网

Php 基于标记的数据库查询

Php 基于标记的数据库查询,php,mysql,database,Php,Mysql,Database,我的桌子是这样的 _________________________________ | product_id | tag_name | |--------------|------------------| | 1 | tag1,tag2,tag3 | | 2 | tag2,tag4,tag6 | | 3 | tag1,tag3 | | 4 | tag4,tag

我的桌子是这样的

 _________________________________
| product_id   | tag_name         |
|--------------|------------------|
|      1       |  tag1,tag2,tag3  |
|      2       |  tag2,tag4,tag6  |
|      3       |  tag1,tag3       |
|      4       |  tag4,tag2,tag1  | 
 ---------------------------------
我想展示产品包含tag3。如何在php中查询数据库

提前谢谢

我把桌子的设计改成了这个

     __________________________
    | tag_id       | tag_name  |
    |--------------|-----------|
    |      1       |  tag1     |
    |      2       |  tag2     |
    |      3       |  tag3     |
    |      4       |  tag4     | 
     --------------------------

     __________________________
    | product_id   |  tag_id   |
    |--------------|-----------|
    |      1       |     1     |
    |      2       |     1     |
    |      3       |     2     |
    |      4       |     3     |
    |      5       |     4     |
    |      6       |     3     | 
     --------------------------

我觉得这个比第一个好。是吗?

一个简单但非常模糊的解决方案是:

SELECT * FROM products WHERE tag_name LIKE '%tag3%'
但是,您的表设计是错误的,您应该有另一个这样的表: 产品标识标签名称 1 tag1 1 tag2 2 tag1使用

但实际上你应该考虑改变你的表格设计。不要在一列中存储多个值 您可以使用比@amik使用的更严格的方法

SELECT * FROM `products` WHERE FIND_IN_SET('tag3', tag_name)

这是一个很好的例子,说明了为什么不应该在一列中存储多个值。在生活变得更艰难之前,现在就规范化你的数据。太模糊了,说实话。谢谢。我认为更好的方法是创建两个表,一个表带有标记名和tagID,另一个表用于创建productID和tagID之间的关系。这是你的意思吗@绝对正确。那最好。
SELECT * FROM `products` WHERE FIND_IN_SET('tag3', tag_name)