【问题标题】:Mssql ORDER BY conditionsMssql ORDER BY 条件
【发布时间】:2017-04-17 20:37:12
【问题描述】:

我想对 sql 查询进行 linq 查询

我的 linq 查询是这样的

 var query3 = from p in _productRepository.Table
                     join bs in query2 on p.Id equals bs.ProductId
                     orderby p.ProductTags.Count(y=>y.Id==locationId)>0
                     select p;

如何在sql查询中实现这个p.ProductTags.Count(y=>y.Id==locationId)>0

【问题讨论】:

  • 您可以使用管理工作室中的 sql profiler 工具捕获您的 qry。即使通过 linq qry,它也会显示与数据库引擎一起使用的完整 tsql 代码。

标签: sql sql-server linq tsql


【解决方案1】:

如果我了解您的 LINQ 查询在做什么,它会先对 ProductTags 中相关计数大于 0 的所有查询进行排序,然后再对其余查询进行排序,但不是按计数排序。在这种情况下,以下查询中的 ORDER BY 将类似:

Select p.*
From ProductRepository As p
Join <query2> As bs On p.ID = bs.ID
Order By Case When (
    Select Count(*) 
    From ProductTags As y 
    Where y.ProductID = p.ID 
      And y.ID = @locationID) > 0 Then 1 Else 0 End;

【讨论】:

    【解决方案2】:
    SELECT productRepository.Id FROM _productRepository.Table
    JOIN *secondtable* 
    WHERE productRepository.Id= *secondtable*.ProductId
    AND  productRepository.Id = locationId
    Group By by productRepository.Id
    Having Count(*) > 0
    ORDER BY COUNT(*)
    

    从 Id 获取其他详细信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-06-19
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 2018-11-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多