【问题标题】:Returning only latest result from LEFT JOIN [duplicate]仅返回 LEFT JOIN 的最新结果 [重复]
【发布时间】:2013-11-01 23:11:28
【问题描述】:

我正在从两个表(students2014 和 notes2014)中查询数据,以便返回学生列表以及每个学生的注释。为此,我使用以下选择语句:

SELECT * 
FROM students2014 
LEFT JOIN notes2014 
ON students2014.Student = notes2014.NoteStudent 
WHERE students2014.Consultant='$Consultant' 
ORDER BY students2014.LastName

这成功地给了我一个列表,但是有多个笔记的学生出现了两次,例如:

  • 学生a - 注意
  • 学生a - 注意
  • 学生 b - 注意
  • 学生 c - 注意

等等……

我只想为每个学生显示最新的笔记,因此每个学生的列表只提供一次。

希望这有意义吗?

【问题讨论】:

    标签: php sql left-join


    【解决方案1】:

    您需要使用子查询连接 studends 表。像这样的东西应该可以工作:

    SELECT * 
    FROM `students2014`
    LEFT JOIN (
        SELECT `note`, `NoteStudent`
        FROM `notes2014`
        HAVING `NoteID` = MAX(`NoteID`)
        GROUP BY `NoteStudent`
    ) `notes`
    ON `students2014`.`Student` = `notes`.`NoteStudent`
    WHERE `students2014`.`Consultant`='$Consultant' 
    ORDER BY `students2014`.`LastName`
    

    【讨论】:

    • 恐怕没有。每张纸币都有一个唯一的 ID,称为 NoteID,它是一个递增的数字,因此最新的纸币具有更高的 ID 号。是否可以使用它?
    • @PhilHowell 好的,已更改查询。它现在使用NoteID。如果它是你所说的auto_increment,那么它应该可以工作
    • 我试过 HAVING NoteID = MAX =(NoteID) 但这似乎不起作用...
    • 不工作是什么意思?意味着您没有收到任何结果?如果是这样,您可以只执行子查询以查看它返回的内容吗?
    • 你能只执行子查询看看它返回什么吗?
    【解决方案2】:

    试试(我不测试,但必须有效):

    SELECT *, MAX(notes2014.notesID) as maxnoteid 
    FROM students2014 
    LEFT JOIN notes2014 ON students2014.Student = notes2014.NoteStudent
    WHERE students2014.Consultant='$Consultant' AND notes2014.notesID = maxnoteid 
    GROUP BY students2014.ID
    ORDER BY students2014.LastName
    

    【讨论】:

      【解决方案3】:
      select
        *
      from
        `students2014`,
        `notes2014`
      where
        `students2014`.`Student` = `notes2014`.`atudent`
        and `notes2014`.`id` in (
          select
          'NoteStudent`,
           max('NoteID`) as`MaxID`
        from
          `notes2014`
        group by
          `NoteStudent`
        )`
      

      【讨论】:

        猜你喜欢
        • 2013-11-28
        • 2012-03-27
        • 2014-05-01
        • 2014-11-15
        • 1970-01-01
        • 1970-01-01
        • 2019-09-06
        • 2015-02-24
        • 1970-01-01
        相关资源
        最近更新 更多