首页 > 解决方案 > 如何在mysql中的一条记录中选择多个值?

问题描述

我有一张有很多列的表。其中一个包含多个参数,如何选择具有此参数之一的字段。例如我的查询是:

select name from product where product='carpet' and selling='new';

销售列包含“新”、“折扣”、..

标签: mysqlsqlcsvselectwhere-clause

解决方案


您正在寻找FIND_IN_SET

如果字符串 str 在由 N 个子字符串组成的字符串列表 strlist 中,则返回 1 到 N 范围内的值。字符串列表是由以 , 字符分隔的子字符串组成的字符串

mysql> DESCRIBE products;
+---------+------------------+------+-----+---------+----------------+
| Field   | Type             | Null | Key | Default | Extra          |
+---------+------------------+------+-----+---------+----------------+
| id      | int(11) unsigned | NO   | PRI | NULL    | auto_increment |
| product | varchar(255)     | YES  |     | NULL    |                |
| selling | varchar(255)     | YES  |     | NULL    |                |
+---------+------------------+------+-----+---------+----------------+
3 rows in set (0.00 sec)

 
mysql> SELECT * FROM products;
+----+---------+---------------------------+
| id | product | selling                   |
+----+---------+---------------------------+
|  1 | carpet  | new,discounted,hello,worl |
|  2 | fork    | used,other                |
|  3 | plate   | new                       |
|  4 | spoon   | NULL                      |
+----+---------+---------------------------+
4 rows in set (0.00 sec)


mysql> SELECT * FROM products
    -> WHERE product='carpet' AND FIND_IN_SET('new', selling) <> 0;
+----+---------+---------------------------+
| id | product | selling                   |
+----+---------+---------------------------+
|  1 | carpet  | new,discounted,hello,worl |
+----+---------+---------------------------+
1 row in set (0.00 sec)

推荐阅读