[英]Comma separated string as field and data - update query in php mysql
[英]Mysql query to search data based on comma separated string of ID's
我有两个表产品和类别表。 在我的网站上,我想根据类别过滤产品。 因此,我将类别ID作为查询字符串传递给URL。 ID以逗号分隔的字符串形式在URL中传递。
我需要一个可以根据类别ID在产品表中进行搜索的MySQL查询或存储过程。
Product Table
| ID | Product_name | Categories |
| 1 | TV 1 | LED, 32 inch, HD |
| 2 | TV 2 | OLED, 55 inch, Ultra HD (4K) |
| 3 | TV 3 | LCD , 24 inch, HD |
| 4 | TV 4 | LED, 55 inch, Full HD |
Category Table
| ID | Category Name |
| 1 | LED |
| 2 | OLED |
| 3 | LCD |
| 4 | 32 inch |
| 5 | 55 inch |
| 6 | 24 inch |
| 7 | HD |
| 8 | Full HD |
| 9 | Ultra HD (4K) |
如果过滤器查询字符串为“ 1,3,7”,则Product表应在输出下面返回
Product Table
| ID | Product_name | Categories |
| 1 | TV 1 | LED, 32 inch, HD |
| 3 | TV 3 | LCD , 24 inch, HD |
MySQL中应使用什么查询或存储过程?
可能的解决方案...
select p.* , count(c.id) as cnt_match
from product as p
join category_table c
where
c.id in ( 1,3,7) and
instr(replace(replace(concat(',',p.categories,','),' ,',','),', ',','),
concat(',',c.categorie_name,','))>0
group by p.id,p.product_name,p.categories;
结果是3行, 电视4是高清
+------+--------------+-----------------------+-----------+
| id | product_name | categories | cnt_match |
+------+--------------+-----------------------+-----------+
| 1 | TV 1 | LED, 32 inch, HD | 2 |
| 3 | TV 3 | LCD , 24 inch, HD | 2 |
| 4 | TV 4 | LED, 55 inch, Full HD | 1 |
+------+--------------+-----------------------+-----------+
AND,因为字段类别中的数据不是干净的,所以您需要添加一些替换项以消除昏迷前后的空间
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.