Using a SELECT statement within a WHERE clause

后端 未结 7 2102
孤街浪徒
孤街浪徒 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:03

    The principle of subqueries is not at all bad, but I don't think that you should use it in your example. If I understand correctly you want to get the maximum score for each date. In this case you should use a GROUP BY.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-12-17 19:09

    Subquery is the name.

    At times it's required, but good/bad depends on how it's applied.

    0 讨论(0)
  • 2020-12-17 19:18

    It's called correlated subquery. It has it's uses.

    0 讨论(0)
  • 2020-12-17 19:22

    It's not bad practice at all. They are usually referred as SUBQUERY, SUBSELECT or NESTED QUERY.

    It's a relatively expensive operation, but it's quite common to encounter a lot of subqueries when dealing with databases since it's the only way to perform certain kind of operations on data.

    0 讨论(0)
  • 2020-12-17 19:22

    In your case scenario, Why not use GROUP BY and HAVING clause instead of JOINING table to itself. You may also use other useful function. see this link

    0 讨论(0)
提交回复
热议问题