2011-01-22 77 views
2

我試圖用Django原始sql查詢like函數,但結果爲空。我嘗試mysql客戶端工具這個查詢並獲得很多記錄。如何解決這個問題?django原始查詢百分號問題

我的查詢:

SELECT s.* , s.id as pk 
    FROM d_status as s, 
     (select post_id 
      from p_useractions 
      where from_user_id in 
       (select to_user_id 
        from p_fallowers 
        where from_user_id = 1) 
     ) as a 
    WHERE s.from_user_id = 1 OR 
     s.text like '%@Mustafa Yontar2123%' OR 
     s.id = a.post_id 
GROUP BY s.id 
ORDER BY s.last_update 
    LIMIT 25 

回答

1

從文檔報價爲MySQL

 
With LIKE you can use the following two wildcard characters in the pattern. 

    Character Description 
    %   Matches any number of characters, even zero characters 
    _   Matches exactly one character 

To test for literal instances of a wildcard character, precede it by the 
escape character. If you do not specify the ESCAPE character, \ is assumed. 

所以,你的模式必須'\%@Mustafa Yontar2123\%'。用於查詢的Python代碼如下所示:

query = r"""SELECT s.* , s.id as pk FROM d_status as s, 
        (SELECT post_id FROM p_useractions WHERE from_user_id in 
        (SELECT to_user_id FROM p_fallowers WHERE from_user_id = 1)) as a 
      WHERE s.from_user_id = 1 or 
        s.text like '\%@Mustafa Yontar2123\%' or 
        s.id = a.post_id 
      GROUP BY s.id 
      ORDER BY s.last_update 
      LIMIT 25""" 

PostgreSQLSQLite文檔提到同樣的事情。

9

嘗試每個%%%更換。因此,您示例中的相關部分應如下所示:'%%@Mustafa Yontar2123%%'

+0

這爲我節省了很多時間!謝謝@gorus我愛你! – Dejell 2016-07-03 14:31:04