Linq -相当于左连接中的BETWEEN

本文关键字:BETWEEN 连接 相当于 Linq | 更新日期: 2023-09-27 18:06:06

我在LINQ中见过这个主题

My Original Query in SQL:

SELECT ISNULL(Tcar.name, '') FROM dbo.models model
LEFT JOIN cars Tcar on Tcar.model = model.id AND
                     Tcar.year between model.Start and model.End

我需要在内部实现一个"左连接",我尝试了这个:

我的类:

public class car
{
    public string name { get; set; }
    public int model { get; set; }
    public DateTime year { get; set; }
}
public class model
{
    public int id { get; set; }
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
}
我实现:

var theModel = from model in models
               join Tcar in cars
                    on new
                        {
                            ID = (int)model.id,
                            DateStart = (DateTime)model.Start,
                            DateEnd = (DateTime)model.End
                        }
                     equals new                                 
                         {
                             ID = (int)Tcar.model,
                             DateStart = (DateTime)Tcar.year,
                             DateEnd = (DateTime)Tcar.year
                         } into tempCar
                       from finalCar in tempCar
               select new
                   {
                       CAR = (finalCar == null ? String.Empty : finalCar.name)
                   };

处理:

var theModel = from model in models
               join Tcar in cars
                    on model.id equals Tcar.model
                where model.Start <= Tcar.year && model.End >= Tcar.year
               select new
                   {
                       CAR = Tcar.name
                   };

如果我使用Linq翻译到这个查询:

SELECT Tcar.name FROM dbo.models model
LEFT JOIN cars Tcar on Tcar.model == model.id
WHERE model.Start <= Tcar.year and model.End >= Tcar.year

我可以在"选择新"之前放一个简单的地方,但我必须通过这种方式实现,在"之间"内部的左连接,我怎么能做到这一点呢?

Linq -相当于左连接中的BETWEEN

Edit -添加DefaultOrEmpty()以使其成为左连接

像这样修改您的查询,这将强制where子句进入join on子句。它不会给你Join中的Between子句,但至少不会有where子句

var theModel = from model in models
               from Tcar in cars.Where(x => model.id == x.model)
                                .Where(x => model.Start <= x.year && model.End >= x.year)
                                .DefaultOrEmpty()
               select new
                   {
                       CAR = Tcar.name
                   };

SQL Server应该认为您的原始查询和LINQ生成的示例是相同的,因为WHERE model.Start <= Tcar.year and model.End >= Tcar.yearON Tcar.year between model.Start and model.End都指定了连接条件。

通常更倾向于使用ON,因为它使您的连接条件与其他搜索条件分开,但这是为了可读性而不是性能。在我周围的几个表上测试类似的查询会产生相同的查询计划,如果您看到不同的表计划,我会感到惊讶。