3

我让这个 SQL 查询工作得很好。我对数据库做了一些小改动,然后重新运行它,它就停止了工作。

master_followups我的目标是加入followups_fb_messages.message_text但只为每个 UID 返回一行,master_followups其中最近followups_fb_messages.message_text加入了它。

SELECT master_followups.*, 
  followups_fb_messages.message_text, 
  followups_fb_messages.message_time 
FROM
  master_followups 
  LEFT JOIN followups_fb_messages 
    ON master_followups.UID = followups_fb_messages.FID 
    AND followups_fb_messages.message_time = 
      (SELECT
        MAX(followups_fb_messages.message_time) 
        FROM followups_fb_messages 
        WHERE  followups_fb_messages.FID = master_followups.UID
      )

我一直试图弄清楚过去一个小时发生了什么。

这不是按预期返回 100 个结果,而是返回 340。我检查了数据库,它显示 100 行 inmaster_followups和 340 行 in followups_fb_messages

大约一个小时前,我有这个确切的查询工作正常,然后它停止了。也许我改变了一些东西,但我看不到它。

4

4 回答 4

2

据推测,您得到重复的原因是不止一行具有最大消息时间。这是解决此问题的一种方法:

 SELECT master_followups.*, 
        ffm.message_text, 
        ffm.message_time 
FROM master_followups LEFT JOIN
     (select *, row_number() over (partition by fid order by message_time desc) seqnum
      from followups_fb_messages
     ) ffm 
     ON master_followups.UID = ffm.FID and
        seqnum = 1

这会根据 message_time 找到最大行,但如果有重复则只选择一行。

于 2012-10-08T01:18:05.143 回答
2

试试这个。

SELECT  a.*, 
        b.*
FROM    master_followups a
        LEFT JOIN followups_fb_messages b
            ON a.UID = b.FID
        LEFT JOIN 
        (
            SELECT  FID, MAX(message_time) maxTime
            FROM    followups_fb_messages
            GROUP BY FID
        ) c ON b.FID = c.FID AND
                b.message_TIME = c.maxTime
于 2012-10-08T01:13:19.650 回答
1

约翰的答案略有修改呢?

SELECT  a.*, 
        b.*
FROM    master_followups a
    LEFT JOIN followups_fb_messages b
        ON (b.FID = c.FID AND b.message_time = c.maxTime)
    LEFT JOIN 
    (
        SELECT  FID, MAX(message_time) maxTime
        FROM    followups_fb_messages
        GROUP BY FID
    ) c ON a.UID = c.FID
于 2012-10-08T01:26:25.677 回答
1

让我们使用一些 TDQD — 测试驱动的查询设计。

每个ID最近的后续消息时间

SELECT FID, MAX(message_time) AS MostRecent
  FROM followups_fb_messages
 GROUP BY FID

每个 ID 的最新后续消息信息

SELECT a.*
  FROM followups_fb_messages AS a
  JOIN (SELECT FID, MAX(message_time) AS MostRecent
          FROM followups_fb_messages
         GROUP BY FID
       ) AS b ON a.FID = b.FID AND a.message_time = b.MostRecent

请注意,这是一个常规的内连接,而不是外连接。

掌握跟进信息和跟进消息信息

SELECT m.*, f.message_text
  FROM master_followups AS m
  LEFT JOIN
       (SELECT a.FID, a.message_text
          FROM followups_fb_messages AS a
          JOIN (SELECT FID, MAX(message_time) AS MostRecent
                  FROM followups_fb_messages
                 GROUP BY FID
               ) AS b ON a.FID = b.FID AND a.message_time = b.MostRecent
       ) AS f ON f.FID = m.UID
于 2012-10-08T01:24:43.367 回答