仅采用满足MySQL中第二个条件的第一个

时间:2019-07-29 13:45:08

标签: c# mysql

我有一个带有日期字段和外键的c#对象。我在这些字段上创建了一个双索引。

public class Session : DbObject
{        
    [DataMember]
    [Column(TypeName = "date")]
    [Index(IsUnique = false, Order = 2)]
    public DateTime Date { get; set; }

    [DataMember]
    [Index(IsUnique = false, Order = 1)]
    public int PatientId { get; set; }

    [DataMember]
    public Patient Patient { get; set; }     
}

我需要从“会议”中获取一个列表,如下所示:我有一个患者ID和日期的列表。我需要为每个患者进行一次会议,以确保其日期是所有其他患者中最新的。

类似这样的东西:

SELECT * FROM Sessions WHERE PatientId IN (1, 2, ...) AND TOP(Date < SOME_DATE)

我知道这个查询是胡说八道。只是为了阐明我的意图。

***使用索引很重要,因为此表很大。

如果可能,我想知道是否可以在c#和实体框架中编写它。

我最近搬到了MySQL。在MS SQL中,我可以使用以下查询解决此问题:

db.Sessions.FromSql(@"
with q as 
( 
   select Date, 
          PatientId, 
          row_number() over (partition by PatientId order by Date desc) rn
   where PatientId in (1,2,3,5,6,3)
     and Date > @d
   from Sessions
)
select Date, PatientId
from q
where rn = 1
", dt);

我在AWS上使用的版本的MySQL中不支持WITH语句的问题。 请帮助翻译查询。

非常感谢!

1 个答案:

答案 0 :(得分:0)

您只能在SQL Server或Mysql中使用GROUP BY。不需要cte:

  select
          PatientId, 
          MAX(`Date`) AS `Date`
   from Sessions
   where PatientId in (1,2,3,5,6,3)
   and Date > @d
   GROUP BY PatientId
相关问题