Using a SELECT statement within a WHERE clause

后端 未结 7 2227
孤街浪徒
孤街浪徒 2020-12-17 18:42
SELECT * FROM ScoresTable WHERE Score = 
  (SELECT MAX(Score) FROM ScoresTable AS st WHERE st.Date = ScoresTable.Date)

Is there a name to describe

7条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 19:08

    This is a correlated sub-query.

    (It is a "nested" query - this is very non-technical term though)

    The inner query takes values from the outer-query (WHERE st.Date = ScoresTable.Date) thus it is evaluated once for each row in the outer query.

    There is also a non-correlated form in which the inner query is independent as as such is only executed once.

    e.g.

     SELECT * FROM ScoresTable WHERE Score = 
       (SELECT MAX(Score) FROM Scores)
    

    There is nothing wrong with using subqueries, except where they are not needed :)

    Your statement may be rewritable as an aggregate function depending on what columns you require in your select statement.

    SELECT Max(score), Date FROM ScoresTable 
    Group By Date
    

提交回复
热议问题