簡體   English   中英

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

[英]How to use a where clause within a MySQL subquery?

我正在使用以下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

它運作良好。 問題是我現在正在嘗試向聊天功能添加群組。 為此,我在chat_messages表中添加了另一列,稱為“ group”。 主要聊天記錄是第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中給出布爾值

按照在該線程上編寫的內容,我嘗試了以下操作,該方法也無效:

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的消息? 我只是不明白它怎么不起作用?

謝謝,

GROUP是MySQL的保留字 ,請在其周圍加上反引號`

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

我不明白為什么要使用子查詢。 第一個選擇類似於第二個選擇,但它會顛倒順序。 使用和ORDER子句查詢MySQL時,它知道正確地對其進行排序。 給定這樣的表(聊天)結構:messageID | posterID | messagetTime | 留言| 組| [其他字段],您可以像這樣選擇它們:

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

這將為您提供最新的20條消息。 正如@bluefeet所說,GROUP是保留字,您應該使用反引號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM