当使用SQL时,在WHERE子句中使用=而不是LIKE有任何好处吗?

没有任何特殊的运算符,LIKE和=是一样的,对吧?


当前回答

=比LIKE快得多。

在有11GB数据和超过1000万条记录的MySQL上测试,f_time列被索引了。

SELECT * FROM XXXXX WHERE f_time = '1621442261' -花费0.00s并返回330条记录

SELECT * FROM XXXXX WHERE f_time like '1621442261' -花费44.71秒并返回330条记录

其他回答

=比LIKE快得多。

在有11GB数据和超过1000万条记录的MySQL上测试,f_time列被索引了。

SELECT * FROM XXXXX WHERE f_time = '1621442261' -花费0.00s并返回330条记录

SELECT * FROM XXXXX WHERE f_time like '1621442261' -花费44.71秒并返回330条记录

在Oracle中,不带通配符的“like”将返回与“equals”相同的结果,但可能需要额外的处理。根据Tom Kyte的说法,Oracle在使用文字时将不带通配符的“like”视为“equals”,但在使用绑定变量时则不会。

要解决最初关于性能的问题,可以归结为索引利用率。当进行简单的表扫描时,“LIKE”和“=”是相同的。当涉及到索引时,这取决于LIKE子句是如何形成的。更具体地说,通配符的位置是什么?


考虑以下几点:

CREATE TABLE test(
    txt_col  varchar(10) NOT NULL
)
go

insert test (txt_col)
select CONVERT(varchar(10), row_number() over (order by (select 1))) r
  from master..spt_values a, master..spt_values b
go

CREATE INDEX IX_test_data 
    ON test (txt_col);
go 

--Turn on Show Execution Plan
set statistics io on

--A LIKE Clause with a wildcard at the beginning
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '%10000'
--Results in
--Table 'test'. Scan count 3, logical reads 15404, physical reads 2, read-ahead reads 15416, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index SCAN is 85% of Query Cost

--A LIKE Clause with a wildcard in the middle
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '1%99'
--Results in
--Table 'test'. Scan count 1, logical reads 3023, physical reads 3, read-ahead reads 3018, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost for test data, but it may result in a Table Scan depending on table size/structure

--A LIKE Clause with no wildcards
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col like '10000'
--Results in
--Table 'test'. Scan count 1, logical reads 3, physical reads 2, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost
GO

--an "=" clause = does Index Seek same as above
DBCC DROPCLEANBUFFERS
SELECT txt_Col from test where txt_col = '10000'
--Results in
--Table 'test'. Scan count 1, logical reads 3, physical reads 2, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.
--Index Seek is 100% of Query Cost
GO


DROP TABLE test

当使用"="和"LIKE"时,在查询计划的创建中也可能存在可以忽略不计的差异。

对于这个例子,我们理所当然地认为varcharcol不包含“并且在这一列上没有空单元格

select * from some_table where varcharCol = ''
select * from some_table where varcharCol like ''

第一个结果是0行输出,而第二个显示整个列表。=是严格匹配的情况下,而like的作用像一个过滤器。如果过滤器没有条件,则每个数据都是有效的。

Like -由于其目的,它的工作速度稍慢,用于varchar和类似的数据。

LIKE和=是不同的。LIKE是在搜索查询中使用的。它还允许像_(简单字符通配符)和%(多字符通配符)这样的通配符。

如果你想要精确匹配,应该使用=,它会更快。

这个网站解释了LIKE