Mysql查询无法使用python脚本

时间:2016-03-21 00:13:06

标签: python mysql

我知道,'不工作'很模糊,但这就是这个剧本正在发生的事情。

我有一个表_added_points的数据库,看起来像这样。

    id  g_id  g_name                       by_score  by_rank  by_percentage
------  ----  ---------------------------  --------  -------  -------------
     1  2332  john-doedd                        307      408         (NULL)
     2  3724  maxx                              844       15         (NULL)
     3  5208  orion-straxee-asset               663      122         (NULL)
     4  8333  Proton                            777       49         (NULL)
     5  9029  contax-dgaaevel                   155      542         (NULL)
     6  6789  clanstrom-e                       803       32         (NULL)
     7  1250  rexx-bundle                       666      119         (NULL)
     8  0236  cluster-performance-toolkit       154      543         (NULL)
     9  0334  gotas                             493      263         (NULL)
    10  3470  pleximoir                         611      163         (NULL)

使用下面的mysql代码,我试图给每个用户percentage计算by_score字段。

SET @total= (SELECT COUNT(*) FROM _added_points);
SELECT s1.g_name, s1.g_id, FLOOR(nge / @total * 100) + 1 AS percent 
FROM _added_points s1
JOIN (SELECT s1.id, COUNT(s2.id) AS nge
    FROM _added_points s1
    JOIN _added_points s2
    ON s1.by_score <= s2.by_score
    GROUP BY s1.id) AS s2
ON s1.id = s2.id
ORDER BY by_score DESC

上面脚本的问题是,当我使用Mysql Workbench或SQLyog的查询构建器运行它时,它可以正常运行..但是当我用python脚本运行它时,我什么也得不到。像这样:

[root@localhost crawler]# python _added_points.py
()

我有多次检查我的python代码是否存在问题,但没有任何问题。即使tryexcept块也无法捕获任何异常。

是否存在可以在mysql客户端上运行的代码,但是在python或php等程序上运行时却没有?它似乎不合逻辑,但这正是发生的事情。

1 个答案:

答案 0 :(得分:2)

尝试执行两个查询,第一个设置用户定义的变量,第二个查询引用变量:

cursor.execute('SET @total= (SELECT COUNT(*) FROM _added_points)')
cursor.execute('''SELECT s1.g_name, s1.g_id, FLOOR(nge / @total * 100) + 1 AS percent 
FROM _added_points s1
JOIN (SELECT s1.id, COUNT(s2.id) AS nge
    FROM _added_points s1
    JOIN _added_points s2
    ON s1.by_score <= s2.by_score
    GROUP BY s1.id) AS s2
ON s1.id = s2.id
ORDER BY by_score DESC''')
相关问题