`SELECT MIN(ZoneMin), MAX(ZoneMin) FROM Plant` as LINQ to SQL

前端 未结 1 1248
忘掉有多难
忘掉有多难 2020-12-06 17:12

This rather simple SQL query is proving to be quite perplexing when attempting it from LINQ.

I have a SQL table Plant with column ZoneMin.<

相关标签:
1条回答
  • 2020-12-06 17:54

    To achieve the same performance as your original query, you'll need to use grouping (by a constant to minimize impact, e.g. 0), so that you can refer to the same set of records twice in the same query. Using the table name causes a new query to be produced on each reference. Try the following:

    (from plant in db.Plants
     group plant by 0 into plants
     select new { Min = plants.Min(p => p.ZoneMin), Max = plants.Max(p => p.ZoneMin) }
    ).Single()
    

    This produces the following query:

    SELECT MIN(plants.ZoneMin), MAX(plants.ZoneMin)
    FROM (SELECT 0 AS Grp, ZoneMin FROM Plants) AS plants
    GROUP BY plants.Grp
    

    And after the optimizer is done with it, it spits out something equivalent to your query, at least according to SQL Server Management Studio.

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