MySQL - NOT LIKE 运算符
MySQL - NOT LIKE 运算符
Section titled “MySQL - NOT LIKE 运算符”本教程解释了如何在 MySQL 中使用 `NOT LIKE` 运算符来过滤不匹配指定字符串模式的数据。我们将涵盖其语法、通配符的使用以及与其他逻辑运算符的组合。您还将学习如何在客户端应用程序中安全地使用它。理解 NOT LIKE 运算符
Section titled “理解 NOT LIKE 运算符”NOT LIKE 运算符是 LIKE 运算符的逻辑非。LIKE 用于查找匹配特定模式的行,而 NOT LIKE 则用于查找所有不匹配该模式的行。它对于基于排除的过滤至关重要。
与其对应物一样,NOT LIKE 依赖于通配符(wildcard characters)来定义匹配模式。
SELECT column1, column2, ...FROM table_nameWHERE column_name NOT LIKE 'pattern';在 NOT LIKE 中使用通配符
Section titled “在 NOT LIKE 中使用通配符”NOT LIKE 的强大之处来自于这两个标准 SQL 通配符:
| 通配符 | 描述 |
|---|---|
| % | 百分号代表零个、一个或多个字符。 |
| _ | 下划线代表正好一个字符。 |
关于高级模式的说明: 对于更复杂的模式匹配,例如字符范围或重复,MySQL 的正则表达式运算符(REGEXP 或 RLIKE,以及它们的否定形式 NOT REGEXP / NOT RLIKE)功能更强大,更灵活。
先决条件:示例数据
Section titled “先决条件:示例数据”让我们在示例中使用 CUSTOMERS 表。
-- 假设 CUSTOMERS 表已按之前的教程创建并填充数据。SELECT * FROM CUSTOMERS;| ID | NAME | AGE | ADDRESS | SALARY |
|---|---|---|---|---|
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | Kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Hyderabad | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
示例:名字不以 ‘K’ 开头
Section titled “示例:名字不以 ‘K’ 开头”要查找所有名字不以字母 ‘K’ 开头的客户:
SELECT * FROM CUSTOMERS WHERE NAME NOT LIKE 'K%';这将排除 ‘Khilan’、‘Kaushik’ 和 ‘Komal’。
示例:地址不以 ‘bad’ 结尾
Section titled “示例:地址不以 ‘bad’ 结尾”要查找所有地址不以 ‘bad’ 结尾的客户:
SELECT * FROM CUSTOMERS WHERE ADDRESS NOT LIKE '%bad';这将排除 ‘Ahmedabad’ 和 ‘Hyderabad’。
示例:名字不包含 ‘al’
Section titled “示例:名字不包含 ‘al’”要查找所有名字不包含子字符串 ‘al’ 的客户:
SELECT * FROM CUSTOMERS WHERE NAME NOT LIKE '%al%';这将排除 ‘Chaitali’ 和 ‘Komal’。
示例:使用下划线 _ 通配符
Section titled “示例:使用下划线 _ 通配符”要查找所有地址的第二个字母不是 ‘o’ 的客户:
SELECT * FROM CUSTOMERS WHERE ADDRESS NOT LIKE '_o%';这将排除 ‘Kota’、‘Bhopal’ 和 ‘Komal’(地址 ‘Hyderabad’)。
将 NOT LIKE 与 AND/OR 结合使用
Section titled “将 NOT LIKE 与 AND/OR 结合使用”您可以通过将 NOT LIKE 与 AND 和 OR 等其他运算符结合使用来创建更复杂的过滤逻辑。
让我们查找名字不以 ‘K’ 开头且地址不以 ‘M’ 开头的客户。
SELECT * FROM CUSTOMERSWHERE NAME NOT LIKE 'K%' AND ADDRESS NOT LIKE 'M%';此查询首先过滤掉所有以 ‘K’ 开头的名字,然后从该结果中进一步过滤掉所有以 ‘M’ 开头的地址。
在独立字符串上使用 NOT LIKE
Section titled “在独立字符串上使用 NOT LIKE”您也可以在不带 FROM 子句的 SELECT 语句中使用 NOT LIKE 来直接测试模式。如果模式不匹配,它返回 1(真);如果匹配,则返回 0(假);如果任一操作数为 NULL,则返回 NULL。
SELECT 'Hello World' NOT LIKE 'Hello%'; -- Result: 0 (because it does match)SELECT 'Hello World' NOT LIKE 'Bye%'; -- Result: 1 (because it does not match)SELECT 'Hello World' NOT LIKE NULL; -- Result: NULL在客户端程序中使用 NOT LIKE
Section titled “在客户端程序中使用 NOT LIKE”当从应用程序中使用 NOT LIKE 时,请务必使用预处理语句安全地传递模式,特别是当它包含用户提供的数据时。这可以防止 SQL 注入。
Node.js(使用 mysql2/promise)
Section titled “Node.js(使用 mysql2/promise)”require('dotenv').config();const mysql = require('mysql2/promise');
async function findCustomers(namePattern) { let connection; try { connection = await mysql.createConnection(process.env.DATABASE_URL || 'mysql://root:password@localhost/your_database'); const query = 'SELECT ID, NAME FROM CUSTOMERS WHERE NAME NOT LIKE ?'; const [rows] = await connection.execute(query, [namePattern]); console.log(`Customers whose name does NOT match '${namePattern}':`); console.log(rows); } catch (error) { console.error('Database query failed:', error.message); } finally { if (connection) await connection.end(); }}
// Find customers whose names do not start with 'K'findCustomers('K%');Python(使用 mysql-connector-python)
Section titled “Python(使用 mysql-connector-python)”import mysql.connectorimport os
def find_customers(name_pattern): connection = None try: connection = mysql.connector.connect( host=os.getenv('DB_HOST', 'localhost'), user=os.getenv('DB_USER', 'root'), password=os.getenv('DB_PASSWORD', 'password'), database=os.getenv('DB_NAME', 'your_database') ) cursor = connection.cursor(dictionary=True) query = "SELECT ID, NAME FROM CUSTOMERS WHERE NAME NOT LIKE %s" cursor.execute(query, (name_pattern,)) results = cursor.fetchall() print(f"Customers whose name does NOT match '{name_pattern}':") for row in results: print(row) except mysql.connector.Error as err: print(f"Database error: {err}") finally: if connection and connection.is_connected(): cursor.close() connection.close()
# Find customers whose names do not end with 'h'find_customers('%h')PHP(使用 PDO)
Section titled “PHP(使用 PDO)”<?phpfunction findCustomers(string $namePattern): void{ $dsn = sprintf("mysql:host=%s;dbname=%s;charset=utf8mb4", $_ENV['DB_HOST'] ?? 'localhost', $_ENV['DB_NAME'] ?? 'your_database' ); $options = [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC];
try { $pdo = new PDO($dsn, $_ENV['DB_USER'] ?? 'root', $_ENV['DB_PASSWORD'] ?? 'password', $options); $stmt = $pdo->prepare('SELECT ID, NAME FROM CUSTOMERS WHERE NAME NOT LIKE :pattern'); $stmt->execute(['pattern' => $namePattern]); $results = $stmt->fetchAll();
echo "Customers whose name does NOT match '{$namePattern}':\n"; print_r($results);
} catch (\PDOException $e) { error_log($e->getMessage()); echo "An error occurred.\n"; }}
// Find customers whose name does not contain 'a'findCustomers('%a%');