【问题标题】:How can I optimize my Linq query?如何优化我的 Linq 查询?
【发布时间】:2012-03-22 07:44:08
【问题描述】:

我有两张桌子Room_masterRoom_Item

Room_Master => roomid - pk, roomname

Room_Item   => roomiteid - pk, roomid - fk, itemid, quantity

我想要一个没有分配任何项目的房间列表。

我已经编写了如下的 SQL 查询来获取结果

select * from room where roomid in 
(select roomid from (select SUM(quantity) as qty, roomid from Room_Item group by roomid )
as newtab where qty=0) order by roomid

我各自的 Linq 查询如下

var roomitem1 = from ri in objEntities.Room_Item
        group ri by ri.roomid into p 
                select new { roomid = p.Key, totalitem = p.Sum(row => row.quantity) };
var roomid  = roomitem1.Where(x => x.totalitem > 0).Select(x => x.roomid);

Linq 查询运行良好,但问题是需要很长时间才能完成 返回数据。我在 Room_master 表中有 6000 条记录,在 Room_item 表中有大约 70000 条记录,大约需要 2 分钟才能将数据返回到我的视图中......

如何优化我的 Linq 查询以使其运行得更快?

【问题讨论】:

  • 如果我正确阅读了您的代码,则 Linq 查询返回的房间 ID 至少分配了一个项目,而您的 SQL 查询返回的房间没有分配任何项目。

标签: sql-server asp.net-mvc linq


【解决方案1】:

完全未经测试:

objEntities.Room_Item
    .GroupBy(ri => ri.RoomId)                 // group all items by room id
    .Where(g => g.Sum(r => r.quantity) == 0)  // where the total quantity of all items for that room id is 0
    .Select(g => g.Key)

应该给你一个没有分配项目的房间ID列表

【讨论】:

  • 效果很好,谢谢@ChrisWue ... :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-04-15
  • 1970-01-01
相关资源
最近更新 更多