LEFT()与LIKE运算符之间的T-SQL速度比较
我正在根据某些 nvarchar
列的第一个字母创建结果分页,而不是通常的一个,通常是按结果数量。
I'm creating result paging based on first letter of certain nvarchar
column and not the usual one, that usually pages on number of results.
我没有面临挑战是否使用 LIKE
运算符或等于( =
)运算符。
And I'm not faced with a challenge whether to filter results using LIKE
operator or equality (=
) operator.
select *
from table
where name like @firstletter + '%'
vs。
select *
from table
where left(name, 1) = @firstletter
我试图在网上搜索两者之间的速度比较,但很难找到任何结果,因为大多数搜索结果与 LEFT JOINs
而不是 LEFT
函数。
I've tried searching the net for speed comparison between the two, but it's hard to find any results, since most search results are related to LEFT JOINs
and not LEFT
function.
是衡量实际生产数据的性能,而不是试图猜测(或问我们)。这是因为效果有时可能取决于您处理的数据,虽然在这种情况下似乎不太可能(但我不是知道,因此你应该检查)。
Your best bet would be to measure the performance on real production data rather than trying to guess (or ask us). That's because performance can sometimes depend on the data you're processing, although in this case it seems unlikely (but I don't know that, hence why you should check).
如果这是一个查询你会做很多,你应该考虑另一个(索引)列包含小写的名字
并通过插入/更新触发器设置。
If this is a query you will be doing a lot, you should consider another (indexed) column which contains the lowercased first letter of name
and have it set by an insert/update trigger.
这将以最小的存储空间增加为代价,使这个查询变得更加快速:
This will, at the cost of a minimal storage increase, make this query blindingly fast:
select * from table where name_first_char_lower = @firstletter
b $ b
这是因为大多数数据库的读取频率远远高于写入数据,这将会摊销所有读取的计算成本(仅对写入操作完成)。
That's because most database are read far more often than written, and this will amortise the cost of the calculation (done only for writes) across all reads.
它引入了冗余数据,但只要您了解(并减轻,如在这个建议中)后果和需要额外的性能,就可以做到这一点。
It introduces redundant data but it's okay to do that for performance as long as you understand (and mitigate, as in this suggestion) the consequences and need the extra performance.