duandeng2011 2019-01-13 09:27
浏览 77

MySQL - 名称包含特定单词的产品名称[复制]

This question already has an answer here:

I have a MySQL table products(id, name, sku) and I have an array of strings: $words = ['1' => 'Carlsberg', '2' => 'Premium', '3' => '250ml'];

How to get from database names of products where product name includes one, two or all words of $words array?

I need some help with writing a sql query to get these products from the database

</div>
  • 写回答

1条回答 默认 最新

  • douhanshu5517 2019-01-13 09:45
    关注

    You can use 'LIKE' or 'REGEXP'. Regexp example shown below:

    $words = ['1' => 'Carlsberg', '2' => 'Premium', '3' => '250ml'];
    $search = implode("|", $words);
    $query = "SELECT id,name,sku FROM products WHERE name REGEXP %{$words}%";
    

    .

    mysql> select * from products;
    +------+------------------------+-------------+
    | id   | name                   | sku         |
    +------+------------------------+-------------+
    |    1 | Carlsberg              | 1094802341  |
    |    2 | Premium Beer 999 300ml | 1093i103    |
    |    3 | Heineken 250ml         | 10901948901 |
    |    4 | Test Product           | 14141414    |
    +------+------------------------+-------------+
    4 rows in set (0.00 sec)
    
    mysql> select * from products WHERE name REGEXP 'Carlsberg|Premium|250ml';   
    
    +------+------------------------+-------------+
    | id   | name                   | sku         |
    +------+------------------------+-------------+
    |    1 | Carlsberg              | 1094802341  |
    |    2 | Premium Beer 999 300ml | 1093i103    |
    |    3 | Heineken 250ml         | 10901948901 |
    +------+------------------------+-------------+
    3 rows in set (0.00 sec)**
    

    Please make sure you use PDO and you sanitize the user inputs first.

    Reference:

    MySQL Like multiple values

    https://www.w3schools.com/sql/sql_like.asp

    评论

报告相同问题?

悬赏问题

  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器