【问题标题】:How to select only the last entry in my table?如何只选择表中的最后一个条目?
【发布时间】:2021-02-19 04:55:56
【问题描述】:

我有表 Matieres 和 Resultats

 ___ Matieres ___            ___ Resultats ___
    id (int auto increment)      ID (int auto_increment)
    Nom (varchar)            TIME_OF_INSERTION (datetime current_timestamp)
    Categorie (varchar)          ID_USER (int)
    Active (boolean)             ID_MATIERE (int)
                                 RESULTAT (int)

我有这个要求:

SELECT * FROM Matieres LEFT JOIN Resultats ON Matieres.id = Resultats.ID_MATIERE AND Resultats.ID_USER = :userid WHERE Active = TRUE AND ID_Formation = :formation)

问题在于,它会为每个 Matieres 返回用户在 Resultats 表中插入的每个结果。当我只想为每个Matieres.Nom 插入最后一个时...:/

我尝试使用GROUP BY TIME_OF_INSERTION ,但它不起作用:(

【问题讨论】:

标签: sql database date join select


【解决方案1】:

你可以使用row_number():

SELECT *
FROM Matieres m LEFT JOIN
     (SELECT r.*,
             ROW_NUMBER() OVER (PARTITION BY id_Matiere, id_user ORDER BY time_of_insertions DESC) as seqnum
      FROM Resultats r
      WHERE r.ID_USER = :userid 
     ) r
     ON m.id = r.ID_MATIERE AND
        seqnum = 1
WHERE Active = TRUE AND ID_Formation = :formation;

【讨论】:

  • 您的 SQL 请求完美运行!问题解决了 ! 1000 倍 thx 给你! :)
【解决方案2】:

尝试在查询末尾添加index 1 以获取最后一条也是唯一一条记录

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2021-10-31
    • 1970-01-01
    • 1970-01-01
    • 2013-11-04
    • 2021-09-20
    • 1970-01-01
    • 2013-05-13
    • 2021-12-12
    相关资源
    最近更新 更多