我正在尝试在我的函数中执行以下操作,但是我收到了一个错误
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '/ (SELECT COUNT(1) FROM users WHERE registered_at BETWEEN '1293861600' AND '1303' at line 1")
我基本上试图将第一个SELECT语句与第二个SELECT语句分开。
cursor.execute( "(SELECT COUNT(1) FROM users WHERE "
" (registered_at BETWEEN '1293861600' AND '1303729537') "
" AND user_id IN ( SELECT parent_id FROM files "
" WHERE created_at > '1293861600')) / "
"(SELECT COUNT(1) FROM users "
"WHERE registered_at BETWEEN '1293861600' AND '1303729537') " )
另外,有没有更好的方法来重写这个查询?
答案 0 :(得分:2)
您可能需要在查询前添加SELECT
。
答案 1 :(得分:1)
cursor.execute( "SELECT COUNT(1) "
" / ( SELECT COUNT(1) FROM users "
" WHERE registered_at BETWEEN '1293861600' AND '1303729537') "
" FROM users "
" WHERE ( registered_at BETWEEN '1293861600' AND '1303729537') "
" AND user_id IN ( SELECT parent_id FROM files "
" WHERE created_at > '1293861600') " )
IN 可以更改为加入:
cursor.execute( " SELECT COUNT(DISTINCT users.user_id) "
" / ( SELECT COUNT(1) FROM users "
" WHERE registered_at "
" BETWEEN '1293861600' AND '1303729537') "
" FROM users "
" JOIN files "
" ON files.parent_id = users.user_id "
" WHERE ( users.registered_at BETWEEN '1293861600' AND '1303729537') "
" AND ( files.created_at > '1293861600') "
)
也可以使用一个子查询重写查询,如下所示:
cursor.execute( " SELECT SUM(IF(user_id IN ( SELECT parent_id "
" FROM files "
" WHERE created_at > '1293861600') "
" ,1 ,0 ) ) "
" / COUNT(1) "
" FROM users "
" WHERE users.registered_at BETWEEN '1293861600' AND '1303729537' "
)
答案 2 :(得分:1)
你需要在整个事情之前进行选择,因此:
cursor.execute( "select (SELECT COUNT(1) FROM users WHERE " ...
答案 3 :(得分:1)
执行以下查询以查看您想要的内容..
SELECT(SELECT COUNT(1)FROM users WHERE registered_at BETWEEN 1293861600 AND 1303729537 AND user_id IN(SELECT parent_id FROM files WHERE created_at> 1293861600))/(SELECT COUNT(1)FROM users WHERE registered_at BETWEEN 1293861600 AND 1303729537)As结果
只有在两个select语句中只得到一个结果时,上述除法才有效。