0

我一直在处理从 MySQL 调用并获得所需内容的问题。我有两个名为项目和条目的表,我想做的是获取最新的时间戳条目。SQL查询如下:

SELECT 
    projects.ProjectLogo, projects.ProjectLink, projects.ProjectDescription, 
    entries.EntryNum, entries.Votes, entries.Views, entries.Update 
FROM 
    projects 
    LEFT JOIN entries 
        ON projects.ProjectID = entries.ProjectID 
        AND projects.Media = 'image' 
        AND projects.Type = 'fan-art' 
GROUP BY 
    projects.ProjectID 
ORDER BY 
    entries.Update DESC

问题是我得到了结果但不是最新的条目,我使用了 MAX(entries.Update) 但它不起作用。有什么建议么?为什么它不起作用?

4

3 回答 3

0

您可以使用子查询来获取Update每个ProjectIDon table的最新信息entries。子查询的结果然后在两个连接语句上重新连接,前提是它将在两列上匹配:ProjectIDUpdate

SELECT  projects.ProjectLogo, 
        projects.ProjectLink, 
        projects.ProjectDescription, 
        entries.EntryNum, 
        entries.Votes, 
        entries.Views, 
        entries.Update 
FROM    projects 
        INNER JOIN entries 
            ON  projects.ProjectID = entries.ProjectID 
        INNER JOIN  
        (
            SELECT  a.ProjectID, MAX(a.Update) max_val
            FROM    entries a
            GROUP   BY a.ProjectID
        ) b ON  b.ProjectID = entries.ProjectID AND
                b.max_val = entries.Update
WHERE   projects.Media = 'image' AND 
        projects.Type = 'fan-art' 
ORDER   BY entries.Update DESC
于 2013-03-21T23:49:37.890 回答
0

您必须将加入限制为仅具有最新输入日期的记录(行)。如果条目中的 pk 是按时间顺序增加的,则可以使用它。

Select p.ProjectLogo, p.ProjectLink, p.ProjectDescription, 
      e.EntryNum, e.Votes, e.Views, e.Update 
From projects p 
   Left Join entries e 
     On e.EntryId =
        (Select(Max(entryId) from entries
         where ProjectID = p.ProjectID)
Where p.Media = 'image' 
    And p.Type = 'fan-art' 
Group By p.ProjectID 
Order By e.Update Desc

否则,您需要一个双嵌套子查询

Select p.ProjectLogo, p.ProjectLink, p.ProjectDescription, 
      e.EntryNum, e.Votes, e.Views, e.Update 
From projects p 
   Left Join entries e 
     On e.EntryId =
        (Select entryId from entries
         where ProjectID = p.ProjectID
            And update =
                (Select max(update) From entries
                 Where ProjectID = p.ProjectID))                        
where p.Media = 'image' 
    And p.Type = 'fan-art' 
Group By p.ProjectID 
Order By e.Update Desc
于 2013-03-21T23:49:48.353 回答
0

尝试使用子查询来获取最新条目:

select projectId, max(`update`) as lastUpdate
from entries
group by projectId

现在,使用这个子查询来获得你需要的东西:

select ...
from 
    projects as p
    inner join entries as e on p.projectId=e.projectId
    inner join (
        select projectId, max(`update`) as lastUpdate
        from entries
        group by projectId) as me on e.`update`=me.lastUpdate

希望这可以帮助你

于 2013-03-21T23:51:12.893 回答