SQL Alchemy ORM和同一查询的Text返回不同的结果?

时间:2016-11-07 20:13:58

标签: python mysql orm sqlalchemy alchemy

我目前在Python中使用SQL Alchemy的文本函数来执行查询以收集有关我的Facebook帖子的统计信息。我试图更新它以使用ORM,但是我得到的结果不同,因为在我看来是相同的查询。例如,一个文本查询如下:

mysql> SELECT COUNT(facebook_posts.id) AS temphold
FROM facebook_posts
WHERE shares < 10  AND account_id=‘12345’ AND article_id IS NOT NULL
AND date(created_time) > '2016-10-01' AND date(created_time) < '2016-10-05';

+----------+
| temphold |
+----------+
|      104 |
+----------+

1 row in set (0.02 sec)

然后使用ORM:

under_10 = session.query(func.count(FacebookPost.id)).\
                         filter(FacebookPost.shares < 10,
                                FacebookPost.account_id == '12345',
                                FacebookPost.article_id != None).\
                        filter(FacebookPost.created_time > start,
                               FacebookPost.created_time < end)

under_10 = session.execute(under_10)

当我打印查询时看起来是相同的:

SELECT count(facebook_posts.id) AS count_1 
FROM facebook_posts 
WHERE facebook_posts.shares < 10 
AND facebook_posts.account_id = '12345' 
AND facebook_posts.article_id IS NOT NULL 
AND facebook_posts.created_time > 2016-10-01 
AND facebook_posts.created_time < 2016-10-05

(150L,)

看起来是一样的,但结果却不同--104 vs 150.为什么会这样?

2 个答案:

答案 0 :(得分:0)

您的SQL语句是错误的语法。 #正在将该行转换为注释,而AND article_id IS NOT NULL尚未实现。尝试将其更改为

...WHERE shares < 10  AND account_id="account#"
 AND article_id IS NOT NULL...

答案 1 :(得分:0)

感谢上面的univerio评论,我一直在寻找如何在SQL Alchemy中指定DATE()并通过将其更改为以下内容来实现它:

under_10 = session.query(func.count(FacebookPost.id)).\
                         filter(FacebookPost.shares < 10, 
                                FacebookPost.account_id == '1234',
                                FacebookPost.article_id != None).\
                        filter(func.date(FacebookPost.created_time) > start,
                               func.date(FacebookPost.created_time) < end)