SELECT FIND_IN_SET(要查找的值, 字符串列表);
CREATE TABLE Products (
product_id INT PRIMARY KEY,
product_name VARCHAR(50),
tags VARCHAR(100)
);
INSERT INTO Products VALUES
(1, 'Laptop', 'Electronics,Large,Portable'),
(2, 'Smartphone', 'Electronics,Portable'),
(3, 'Tablet', 'Electronics,Portable');
-- 1. 查找包含标签 'Large' 的产品
SELECT product_name, FIND_IN_SET('Large', tags) AS tag_position
FROM Products
WHERE FIND_IN_SET('Large', tags) > 0;
-- 注释:返回包含标签 'Large' 的产品及其在标签列表中的位置
-- 2. 查找包含标签 'Portable' 的产品
SELECT product_name, FIND_IN_SET('Portable', tags) AS tag_position
FROM Products
WHERE FIND_IN_SET('Portable', tags) > 0;
-- 注释:返回包含标签 'Portable' 的产品及其在标签列表中的位置
-- 1. 查找包含标签 'Large' 的产品
SELECT product_name, FIND_IN_SET('Large', tags) AS tag_position
FROM Products
WHERE FIND_IN_SET('Large', tags) > 0;
-- 结果:
/*
| product_name | tag_position |
|--------------|--------------|
| Laptop | 2 |
*/
-- 2. 查找包含标签 'Portable' 的产品
SELECT product_name, FIND_IN_SET('Portable', tags) AS tag_position
FROM Products
WHERE FIND_IN_SET('Portable', tags) > 0;
-- 结果:
/*
| product_name | tag_position |
|--------------|--------------|
| Laptop | 3 |
| Smartphone | 2 |
| Tablet | 2 |
*/
-- 错误示例:未指定要查找的值
SELECT FIND_IN_SET('', tags);
-- 错误原因:需要指定要查找的值,不能是空字符串
-- 错误示例:未指定字符串列表
SELECT FIND_IN_SET('Portable', '');
-- 错误原因:需要指定逗号分隔的字符串列表