3

我有一个可以包含主要消息以及子消息的消息表。我想要实现的只是获得前 2 个最近的子消息。

SELECT message.id, message.date_sent,message.object_id, message.content, 
       SubMessage1.content, SubMessage1.id, SubMessage1.date_sent,
       SubMessage2.content, SubMessage2.id, SubMessage2.date_sent
  FROM messages As Message 
  LEFT
 OUTER
  JOIN ( SELECT messages.object_id as object_id, messages.content as content,
                messages.id as id , messages.date_sent as date_sent
           FROM messages
          ORDER
             BY messages.date_sent ASC LIMIT 1,1
       ) as SubMessage1
    ON Message.id = SubMessage1.object_id
  LEFT
 OUTER
  JOIN ( SELECT messages.object_id as object_id, messages.content as content,
                messages.id as id , messages.date_sent as date_sent
           FROM messages
          ORDER
             BY messages.date_sent ASC LIMIT 2,1
       ) as SubMessage2
    ON Message.id = SubMessage2.object_id
 WHERE Message.id = 1

当我删除限制时,我总是得到第一个结果。但是当我输入限制时,我得到空值。有任何想法吗?建议?

4

4 回答 4

1

这里的问题是ORDER BY ... LIMIT ...in 子查询在in 连接之前ON Message.id = ... .object_id应用。因此,连接只有机会检查一条消息并确定它是否是子消息。大多数时候,它不会,所以你会得到NULL价值。

要解决此问题,您需要将ON-clauses 的内容移动到WHERE子查询内的 -clauses 中。通常这会有点混乱,但是由于您只想检索单记录结果集,所以还不错:

SELECT message.id, message.date_sent, message.object_id, message.content, 
       SubMessage1.content, SubMessage1.id, SubMessage1.date_sent,
       SubMessage2.content, SubMessage2.id, SubMessage2.date_sent
  FROM messages AS Message 
  LEFT
 OUTER
  JOIN ( SELECT messages.object_id AS object_id, messages.content AS content,
                messages.id AS id, messages.date_sent AS date_sent
           FROM messages
          WHERE messages.object_id = 1
          ORDER
             BY messages.date_sent ASC LIMIT 1,1
       ) AS SubMessage1
    ON TRUE
  LEFT
 OUTER
  JOIN ( SELECT messages.object_id AS object_id, messages.content AS content,
                messages.id AS id, messages.date_sent AS date_sent
           FROM messages
          WHERE messages.object_id = 1
          ORDER
             BY messages.date_sent ASC LIMIT 2,1
       ) AS SubMessage2
    ON TRUE
 WHERE Message.id = 1
;

(请注意,这在查询中包含三次参数:可能不太理想,但实际上不是问题。)

于 2012-11-29T22:41:50.613 回答
1
SELECT * FROM messages WHERE id = 1
Union all
SELECT * FROM messages WHERE object_id=1
ORDER BY date_sent ASC LIMIT 2
于 2012-11-29T22:26:48.687 回答
0

如果你想要 2 行,请使用

LIMIT 2

在 SQL 领域,计数是从 1 而不是 0。

此外,在具有 2 个参数的 mysql LIMIT 中是:

LIMIT offset, row_count

但是使用 1 个参数是:

LIMIT row_count

我想见见那个决定像那样移动参数并踢他的裤子的天才。

于 2012-11-29T22:24:44.290 回答
-1

LIMIT 命令的起始索引为 0。您可能希望将限制更改为 (0, 1) 和 (1, 1)。

于 2012-11-29T22:36:30.850 回答