【问题标题】:Fetching a big number of records using JOIN使用 JOIN 获取大量记录
【发布时间】:2015-03-02 18:25:48
【问题描述】:

我有这个查询,用于从多个表中获取记录,使用 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

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

【问题讨论】:

  • 你的列索引完成了吗
  • 你需要什么submission AS s那里?
  • 你不能把你的 GROUP BY 和聚合函数放在一起吗?!?这非常令人困惑。

标签: mysql sql


【解决方案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

【讨论】:

    【解决方案2】:

    可以更改查询结果的行限制,或完全取消限制。

    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

    【讨论】:

      猜你喜欢
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2018-07-16
      • 1970-01-01
      • 2017-11-19
      • 2016-02-11
      相关资源
      最近更新 更多