我在like
函数中尝试Django原始sql查询,但结果为空。我尝试mysql客户端工具这个查询并获得许多记录。如何解决这个问题?
我的疑问:
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
答案 0 :(得分:12)
尝试用%
替换每个%%
。因此,示例中的相关部分如下所示:'%%@Mustafa Yontar2123%%'
。
答案 1 :(得分:2)
引用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"""
PostgreSQL和SQLite的文档提到了同样的事情。