2011-04-25 157 views
0

我想執行我的功能,下面,但我得到一個錯誤 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') ") 

此外,有沒有更好的方式來重新編寫此查詢?

回答

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能化作JOIN

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

你可能需要在您的查詢前加上SELECT

1

你一個選擇整個事情之前需要,即:

cursor.execute("select (SELECT COUNT(1) FROM users WHERE " ... 
1

執行下面的查詢,看你想要什麼..

SELECT(SELECT COUNT(1)FROM用戶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 Results

如果您只有一個結果,這兩個本身選擇語句。