![](/img/trans.png)
[英]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.