SQL INNER JOIN LIMIT RESULTS ID唯一且日期最近

时间:2017-10-18 21:45:45

标签: php mysql sql join

我是SQL的新手,正在处理一个select语句,该语句应该返回一个表结果,如下所示。目标是为每个存在的ThreadID返回一行表,并且具有与要查询的CatID匹配的CatID,然后过滤结果/限制结果,以便仅返回最新的帖子并返回基于排序的结果在创建日期:

修改日期修改后的日期更加明显我希望从哪个日期返回每个可能的行(最近的日期,其中CatID = 1)如果数据存在于一个表中,我可以写这个,我想,但这显然超出了我的理解

╔══════════╔══════════╦═══════════════╦════════╦═════════════╗ 
║  CatID   ║ ThreadID ║  ThreadTitle  ║ PostID ║ DateCreated ║
╠══════════╬══════════╬═══════════════╬════════╬═════════════╣
║    4     ║     7    ║    Title A    ║   12   ║ most recent ║
║    4     ║     6    ║    Title B    ║   6    ║ most recent ║
║    4     ║     12   ║    Title C    ║   45   ║ most recent ║
║    4     ║     3    ║    Title D    ║   2    ║ most recent ║
╚══════════╩══════════╩═══════════════╩════════╩═════════════╝

我一直在阅读PHPfreaks,W3schools,显然是StackOverflow并试图使用Adminer建模我的结果。我已经学到了一些关于加入的知识,我之前没有尝试过,但是经过几个小时的尝试(6小时)后,我觉得自己很乐意寻求帮助。

我的尝试要么没有产生任何结果,要么产生1个结果,要么产生8000+个结果。我的实际测试数据应该有4个结果。

这是我最近尝试的sql,它没有按预期工作

SELECT
    mat.ThreadTitle,
    mat.CatID,

    map.DateCreated AS "RecentID",
    map.ThreadID,
    map.LastUpdated


    FROM
            ma_Threads AS mat
    INNER JOIN
            ma_Posts AS map

    ON mat.CatID = '$catID' 

WHERE       `pat.DateCreated(test.marvelchampions)` = (
 SELECT MAX(DATE(pat.DateCreated))
 FROM `pat`

2 个答案:

答案 0 :(得分:1)

假设我对表的定义是正确的猜测

,以下情况应该有效
SELECT
  ma_Threads.CatID,
  ma_Threads.ID AS ThreadID,
  ma_Threads.ThreadTitle,
  ma_Posts.ID AS PostID,
  ma_Posts.LastUpdated

FROM ma_Threads
JOIN ma_Posts ON (
    ma_Posts.ID = (
        SELECT MAX(ma_Posts2.ID)
        FROM ma_Posts ma_Posts2
        WHERE ma_Posts2.ThreadID = ma_Threads.ID
    )
)
WHERE ma_Threads.CatID = '$catID'
ORDER BY ma_Posts.LastUpdated DESC

答案 1 :(得分:0)

没有看到你的桌子就很难说。但我最好的猜测是:

SELECT mat.ThreadTitle,
       mat.CatID,
       map.DateCreated AS "RecentID",
       map.ThreadID,
       MAX(map.LastUpdated)
FROM ma_Threads AS mat
INNER JOIN ma_Posts AS map
ON mat.CatID = map.CatID
GROUP BY mat.ThreadTitle, mat.CatID, map.DateCreated, map.ThreadID