详细的SQL查询,count(*)限制器无法正常工作

时间:2012-06-12 21:19:41

标签: python mysql mysql-python

我担心我对SQL没有好感,所以我对此遇到麻烦并不感到惊讶,但是如果你可以帮助我让它工作(甚至不必是一个查询),我将不胜感激。试图用Python中的MySQLdb分析一些Twitter数据,我正在运行:

for u_id in list:
"
select e.user_id
from table_entities e
inner join table_tweets t on e.id = t.id
where e.type='mention' and t.user_id=%s
group by e.type having count('hashtag') < 3
"
%
(u_id)

(python语法稍微伪造,不显示不重要的东西)

现在,“group by”声明之前的所有内容都可以正常工作。我能够提取给定推文中提到的user_ids(id是table_tweets的PK,而table_entities中的每一行,每个提及,主题标签或URL)与我的循环的当前位置匹配。

然而 - 我不认为我在任何地方正确地格式化它 - group by语句没有做任何事情。我的意思是排除所有属于推文(id)的user_id,这些推文在table_entity中有3个或更多条目,类型为= hashtag。我可以告诉它不会按原样运行,因为它实际上并没有引用id列,而是我试图做的任何方式(例如通过尝试使其成为join子句的一部分)抛出语法错误。

建议表示赞赏!

2 个答案:

答案 0 :(得分:0)

这并不是你想要的。

select e.user_id
from table_entities e
inner join table_tweets t on e.id = t.id
where e.type='mention' and t.user_id=%s
group by e.type having count('hashtag') < 3
  • Select And group by子句没有按预期执行。通过将e.user_id放在SELECT子句而不是GROUP BY MySQL中,将为每个e.type选择一个任意user_id。
  • Having count('literalString')相当于Having COUNT(*)您可以通过将Count('hashtag')移动到select子句来自行查看。

以下是Live DEMO这些要点

结果是您的查询仅记录用户提及的次数少于3次。

有很多方法可以完成你选择的尝试IN(你也可以使用Exists或INNER JOIN到子查询)

SELECT e.user_id 
FROM   table_entities e 
       INNER JOIN table_tweets t 
               ON e.id = t.id 
WHERE  e.type = 'mentions' 
       AND t.user_id =% s 
       AND e.user_ID  IN (SELECT e.user_id 
                             FROM   table_entities e 
                                    INNER JOIN table_tweets t 
                                            ON e.id = t.id 
                             WHERE  e.type = 'hashtag' 
                                    AND t.user_id =% s 
                             GROUP  BY e.user_id 
                             HAVING Count(*) >= 3) 

sub select查找table_enties中记录少于3条记录的所有用户ID,其中e.type为“hashtag”,用户匹配% s

“提及”的主要选择过滤器和用户ID。这允许您选择一个e.type并过滤另一个e.type的计数。

答案 1 :(得分:0)

我认为你错误地解析了我帖子的一部分(我的错误是因为它有点混乱) - 只有当type ='提及'时才会填充user_id列。我试图通过 id 列进行限制。那说,感谢你的帮助,我能够让它发挥作用!

select e.user_id
from table_entities e
inner join table_tweets t on e.id = t.id
where e.type='mention' and
e.id in
(select e.id
from table_entities e
where e.type='hashtag' group by e.id having count(*) < 3)

我决定将它移到列表循环中的u_id之上,因为查询现在需要一段时间才能运行,但我可以在这里使用列表输出就好了。谢谢!