简体   繁体   English

SQL查询的Where子句数月和数年

[英]Where clause for SQL query for months and years

I've written an Sql query with a where clause narrowing the result to be with start month start year and end month end year . 我编写了一个带where子句的Sql查询,将结果范围缩小为start month start yearend month end year Please find below the part with where clause (my query is quite complex so I don't want to give all its details): 请在下面找到带有where子句的部分(我的查询非常复杂,因此我不想提供所有详细信息):

SELECT *
  FROM foo
  WHERE (year, month) between (startYear, startMonth) and (endYear, endMonth);

Note thatI find it to be very easy to understand and very expressive. 请注意,我发现它非常易于理解和表达。 How about its speed? 速度如何? Are there faster alternatives? 有更快的选择吗? If so, how would they look like? 如果是这样,它们的外观如何?

In general, when you write SQL queries, you shouldn't really worry about speed. 通常,在编写SQL查询时,您不必真正担心速度。 A mature SQL server will select a reasonable execution plan for you. 成熟的SQL Server将为您选择合理的执行计划。 So your query is probably fine. 因此,您的查询可能很好。 There are a few things though that you can check: 您可以检查以下几件事:

  • You can check whether there are indexes for the columns in your where clause. 您可以检查where子句中的列是否有索引。
  • If there are compound indexes then you can make sure to use the columns in the same order they appear in the index definition. 如果有复合索引,则可以确保以与列在索引定义中出现的顺序相同的方式使用这些列。
  • You can make sure to use search arguments in your WHERE clauses. 您可以确保在WHERE子句中使用搜索参数 In a nutshell it means not to make calculation on a column value before comparing to it. 简而言之,这意味着在与列值进行比较之前不对它进行计算。

If this speed is not good enough for you, then you can tune the indexes for your query. 如果此速度对您来说不够好,则可以调整查询的索引。 Ie add indexes that match your where clauses. 即添加与您的where子句匹配的索引。 Some RDBMS-s let you partition your tables by date. 一些RDBMS允许您按日期对表进行分区。 Sometimes you can replace one complex query with a few simple queries and temporary tables. 有时,您可以用一些简单查询和临时表替换一个复杂查询。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM