子查询中的限制

时间:2012-11-29 21:58:49

标签: mysql sql

我有一个可以包含主要消息的消息表,以及子消息。我想要实现的只是获得前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 个答案:

答案 0 :(得分:1)

SELECT * FROM messages WHERE id = 1
Union all
SELECT * FROM messages WHERE object_id=1
ORDER BY date_sent ASC LIMIT 2

答案 1 :(得分:1)

这里的问题是子节点中的ORDER BY ... LIMIT ...在连接中的ON Message.id = ... .object_id之前被应用。因此,联接只有机会检查一个消息并确定它是否是子消息。大多数情况下,它不会,因此您将获得NULL值。

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

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
;

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

答案 2 :(得分:0)

如果您想要2行,请使用

LIMIT 2

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

另外,在mysql LIMIT中有2个参数:

LIMIT offset, row_count

但是有1个参数:

LIMIT row_count

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

答案 3 :(得分:-1)

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