Beginner SQL section: avoiding repeated expression

后端 未结 5 987
-上瘾入骨i
-上瘾入骨i 2021-02-14 15:45

I\'m entirely new at SQL, but let\'s say that on the StackExchange Data Explorer, I just want to list the top 15 users by reputation, and I wrote something like this:

         


        
5条回答
  •  长发绾君心
    2021-02-14 16:12

    Regarding something like named expressions, while there are several possible alternatives, the query optimizer is going to do best just writing out the formula Reputation / 1000 long-hand. If you really need to run a whole group of queries using the same evaluated value, your best bet is to create view with the field defined, but you wouldn't want to do that for a one-off query.

    As an alternative, (and in cases where performance is not much of an issue), you could try something like:

    SELECT TOP 15
        DisplayName, Id, Reputation, RepInk
    FROM (
         SELECT DisplayName, Id, Reputation, Reputation / 1000 as RepInk
         FROM Users
    ) AS table
    WHERE table.RepInk > 10
    ORDER BY Reputation DESC
    

    though I don't believe that's supported by all SQL dialects and, again, the optimizer is likely to do a much worse job which this kind of thing (since it will run the SELECT against the full Users table and then filter that result). Still, for some situations this sort of query is appropriate (there's a name for this... I'm drawing a blank at the moment).

    Personally, when I started out with SQL, I found the W3 schools reference to be my constant stopping-off point. It fits my style for being something I can glance at to find a quick answer and move on. Eventually, however, to really take advantage of the database it is necessary to delve into the vendors documentation.

    Although SQL is "standarized", unfortunately (though, to some extent, fortunately), each database vendor implements their own version with their own extensions, which can lead to quite different syntax being the most appropriate (for a discussion of the incompatibilities of various databases on one issue see the SQLite documentation on NULL handling. In particular, standard functions, e.g., for handling DATEs and TIMEs tend to differ per vendor, and there are other, more drastic differences (particularly in not support subselects or properly handling JOINs). If you care for some of the details, this document provides both the standard forms and deviations for several major databases.

提交回复
热议问题