【问题标题】:Mysql query to search data based on comma separated string of ID'sMysql查询基于ID的逗号分隔字符串搜索数据
【发布时间】:2019-08-07 18:26:56
【问题描述】:

我有两个表产品和类别表。在我的网站上,我想根据类别过滤我的产品。因此,我将类别 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 Table

| ID | Product_name | Categories        |
| 1  | TV 1         | LED, 32 inch, HD  |
| 3  | TV 3         | LCD , 24 inch, HD |

MySQL 中应该有什么查询或存储过程?

【问题讨论】:

  • Stackoverflow 不是免费的代码编写服务。我们修复了您失败的尝试。向我们展示您已经研究并尝试自我解决。您应该在 Product 表中使用 Category 表中的 id。
  • 你需要规范化数据,en.wikipedia.org/wiki/First_normal_form你现在的结构会很难使用和维护
  • 我希望您尝试为自己制作的查询将包括:FIND_IN_SET()w3resource.com/mysql/string-functions/…,但该函数表明可以实现进一步的规范化。

标签: php mysql stored-procedures


【解决方案1】:

一个可能的解决方案...

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 行,TV 4HD

+------+--------------+-----------------------+-----------+
| 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因为字段categories的数据不干净,需要加一些replace去掉逗号前后的空格

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多