我想写一个如下所示的SQL语句:
select * from tbl where col like ('ABC%','XYZ%','PQR%');
Run Code Online (Sandbox Code Playgroud)
我知道可以用它来完成OR.但我想知道有没有更好的解决方案.
Bil*_*win 60
这是一个很好的临时表使用.
CREATE TEMPORARY TABLE patterns (
pattern VARCHAR(20)
);
INSERT INTO patterns VALUES ('ABC%'), ('XYZ%'), ('PQR%');
SELECT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);
Run Code Online (Sandbox Code Playgroud)
在示例模式中,col无法匹配多个模式,因此您可以确保tbl在结果中最多只能看到一行.但是,如果您的模式col可以匹配多个模式,则应使用DISTINCT查询修饰符.
SELECT DISTINCT t.* FROM tbl t JOIN patterns p ON (t.col LIKE p.pattern);
Run Code Online (Sandbox Code Playgroud)
Asa*_*aph 42
这是另一种方式:
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
Run Code Online (Sandbox Code Playgroud)
以下是验证的测试代码:
create table tbl (col varchar(255));
insert into tbl (col) values ('ABCDEFG'), ('HIJKLMNO'), ('PQRSTUVW'), ('XYZ');
select * from tbl where col like 'ABC%'
union
select * from tbl where col like 'XYZ%'
union
select * from tbl where col like 'PQR%';
+----------+
| col |
+----------+
| ABCDEFG |
| XYZ |
| PQRSTUVW |
+----------+
3 rows in set (0.00 sec)
Run Code Online (Sandbox Code Playgroud)
小智 39
Oracle 10g具有允许在SQL中使用符合POSIX的正则表达式的函数:
有关此函数的语法详细信息,请参阅Oracle数据库SQL参考.
代码:
select * from tbl where regexp_like(col, '^(ABC|XYZ|PQR)');
Run Code Online (Sandbox Code Playgroud)
这可能有帮助:
select * from tbl where col like '[ABC-XYZ-PQR]%'
Run Code Online (Sandbox Code Playgroud)
我在 SQL Server 2005 中使用过它并且它有效。
小智 5
select * from tbl where col like 'ABC%'
or col like 'XYZ%'
or col like 'PQR%';
Run Code Online (Sandbox Code Playgroud)
这适用于蟾蜍和powerbuilder。不知道其余的
小智 5
我也有同样的要求,我无法选择通过执行 OR 或编写联合查询来多次传递 like 运算符。
This worked for me in Oracle 11g:
REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
353517 次 |
| 最近记录: |