FIELD() 是 MySQL 中的一个字符串函数,用于返回一个值在给定列表中的位置索引(从1开始计数)。这个函数在需要根据特定顺序对结果进行排序或比较时非常有用。
FIELD(str, str1, str2, str3, ...)str:要查找的值str1, str2, str3, ...:要搜索的值列表str,返回它在列表中的位置(从1开始)SELECT FIELD('b', 'a', 'b', 'c', 'd'); -- 返回 2假设有一个产品表 products:
CREATE TABLE products (
id INT PRIMARY KEY,
name VARCHAR(50),
category VARCHAR(20)
);
INSERT INTO products VALUES
(1, 'Laptop', 'Electronics'),
(2, 'Phone', 'Electronics'),
(3, 'Desk', 'Furniture'),
(4, 'Chair', 'Furniture'),
(5, 'Monitor', 'Electronics');我们可以使用 FIELD() 函数按特定顺序排序:
SELECT * FROM products
ORDER BY FIELD(category, 'Electronics', 'Furniture');结果将首先显示所有 'Electronics' 类别的产品,然后是 'Furniture' 类别的产品。
FIELD() 函数常用于自定义排序顺序:
SELECT name, category,
FIELD(category, 'Electronics', 'Furniture', 'Clothing') AS sort_order
FROM products
ORDER BY sort_order;SELECT FIELD('Book', 'a', 'b', 'c') AS position; -- 返回 0