如何在MySQL子查询中使用where子句?

时间:2012-08-23 11:56:32

标签: mysql subquery where-clause

我使用以下MySQL查询来访问聊天记录中的最新20条消息并反转订单,以便最后在屏幕上打印最新消息:

SELECT * 
FROM 
    (
        SELECT
            messageID,
            posterID,
            messageTime,
            message
        FROM
            chat_messages
        /* Subquery is used to get the most recent 20 by messageTime */
        ORDER BY 
            messageTime DESC
        LIMIT 20
    ) subq
/* Reorder the result of the subquery to put them back into ascending order */
ORDER BY 
    messageTime ASC

效果很好。问题是我现在正在尝试向聊天功能添加组。在这样做的过程中,我在名为“group”的chat_messages表中添加了另一列。主聊天日志是组0,因此我需要更改上述查询以仅访问主聊天日志中的消息。这是我被困的地方。似乎MySQL不允许我在子查询中添加where子句。我尝试过以下操作但没有用:

SELECT * 
FROM 
    (
        SELECT
            messageID,
            posterID,
            messageTime,
            message
        FROM
            chat_messages
        WHERE
            group = '0'
        /* Subquery is used to get the most recent 20 by messageTime */
        ORDER BY 
            messageTime DESC
        LIMIT 20
    ) subq
/* Reorder the result of the subquery to put them back into ascending order */
ORDER BY 
    messageTime ASC

我收到此错误消息(第58行是查询后的下一行):

  

警告:mysql_num_rows()期望参数1为资源,第58行的xxxxxxx中给出布尔值

按照this thread上的内容,我尝试了以下操作,但也没有用:

SELECT * 
FROM 
    (
        SELECT
                (
                    SELECT
                        messageID,
                        posterID,
                        messageTime,
                        message
                    FROM
                        chat_messages
                    WHERE
                        group = '0'
                )
        FROM
            chat_messages
        /* Subquery is used to get the most recent 20 by messageTime */
        ORDER BY 
            messageTime DESC
        LIMIT 20
    ) subq
/* Reorder the result of the subquery to put them back into ascending order */
ORDER BY 
    messageTime ASC

如何使查询仅访问组0中的消息?我只是不明白它是如何起作用的?

谢谢你,

2 个答案:

答案 0 :(得分:1)

GROUP是MySQL的reserved word,在其周围加上`

SELECT * 
FROM 
(
     SELECT messageID,
          posterID,
          messageTime,
          message
     FROM chat_messages
     WHERE `group` = '0'
        /* Subquery is used to get the most recent 20 by messageTime */
     ORDER BY  messageTime DESC
     LIMIT 20
 ) subq
/* Reorder the result of the subquery to put them back into ascending order */
ORDER BY  messageTime ASC

答案 1 :(得分:0)

我不明白你为什么使用子查询。第一个选择就像第二个选择一样,除了它颠倒顺序。 使用和ORDER子句查询MySQL时,它知道正确排序它们。 给定一个像这样的表(聊天)结构: messageID | posterID | messagetTime |消息|小组| [其他领域], 你可以这样选择:

SELECT messageID, posterId, messageTime, message FROM chat WHERE `group` = [number] ORDER BY messageTIME DESC LIMIT 20

这将为您提供最新的20条消息。 正如@bluefeet所说,GROUP是一个保留字,你应该使用反引号。