使用JOIN获取大量记录

时间:2015-01-05 08:26:51

标签: mysql sql

我使用此查询来使用JOIN从多个表中获取记录。

SELECT c.id           AS contestant_id,
       c.created_date,
       c.name         AS contestant_name,
       counter.total  AS score,
       c.email
  FROM submission AS s,

       (SELECT ans.id AS ans_id, sub.contestant_id, count(sub.id) AS total
          FROM submission AS sub
          JOIN (SELECT id, is_true FROM answer) AS ans
         WHERE sub.answer_id = ans.id
           AND ans.is_true = 1
         GROUP BY sub.contestant_id) AS counter

  JOIN (SELECT id, name, email, type, created_date
          FROM contestant
         WHERE contest_type = 1
           AND submission_status = 1) AS c

 WHERE counter.contestant_id = c.id
 GROUP BY c.id
 ORDER BY c.created_date DESC

问题是表参赛者中的每条记录在提交表中都有30条记录。因此,当我检索1000名参赛者或更多时,服务器会挂起。

2 个答案:

答案 0 :(得分:1)

请尝试以下重组查询:

SELECT 
    c.id AS contestant_id, 
    c.created_date, 
    c.name AS contestant_name, 
    counter.total AS score, 
    c.email
FROM 
    (
      SELECT  
        sub.contestant_id, count(sub.id) AS total
      FROM 
        submission AS sub 
        JOIN answer AS ans
            ON sub.answer_id = ans.id AND ans.is_true = 1 
      GROUP BY 
        sub.contestant_id
    )
    AS counter
    JOIN contestant c
      ON c.contest_type = 1 AND c.submission_status = 1 AND c.id = counter.contestant_id
WHERE 
    counter.contestant_id = c.id 
GROUP BY 
    c.id 
ORDER BY 
    c.created_date DESC

答案 1 :(得分:0)

可以更改查询结果行限制,或完全删除限制。

Go to "Edit -> Preferences... -> SQL Editor (tab)"

Locate the "Query Results" section and untick the "Limit Rows" checkbox

Click "OK"

Re-run your query

Exporting query results in MySQL Workbench beyond 1000 records