2011-07-28 82 views
3

即時嘗試使用CodeIgniter和Datatables.net生成報告。MySQL中的緩慢子查詢

現在我正在嘗試關閉的工作量(其人力資源系統)。我曾經查詢過所有的工作,並在PHP中做了一個foreach,然後做了calcs。

因爲我想使用Datatables的所有功能(特別排序)即時嘗試在mySQL中做所有的計算。

問題是:第二個子查詢非常非常慢。

SELECT 
jobs.jobs_id, clients.nome_fantasia, concat_ws(' ', user_profiles.first_name, user_profiles.last_name) as fullname, 
jobs.titulo_vaga, jobs.qtd_vagas, company.name as nome_company, jobs_status.name as  status_name, DATEDIFF(NOW(), jobs.data_abertura) as date_idade, 
(select count(job_cv.jobs_id) from job_cv where job_cv.jobs_id = jobs.jobs_id) as qtd_int, 
(select count(distinct job_cv.user_id) from job_cv_history join job_cv on job_cv.job_cv_id = job_cv_history.job_cv_id where job_cv_history.status = '11' and job_cv.jobs_id = jobs.jobs_id) as fechadas 
FROM (jobs) 
JOIN clients ON lients.clients_id=jobs.clients_idJOIN user_profiles ON jobs.consultor_id=user_profiles.user_id 
JOIN jobs_status ON jobs.status=jobs_status.jobs_status_id 
JOIN company ON jobs.company_id=company.company_id 
LIMIT 50 

有人能幫幫我嗎?如果需要,我可以提供更多信息。

UPDATE

的主意,使用JOIN改爲選擇工作與第一子查詢,但與第二個不是,有沒有辦法通過一個「變量」子查詢中使用?像當前的jobs_id一樣?

再次更新

該行正常工作本身。但在subquery裏面用worng值需要一分鐘左右

SELECT job_cv.jobs_id,count(distinct job_cv.user_id) AS fechadas 
FROM job_cv_history 
JOIN job_cv 
ON job_cv.job_cv_id = job_cv_history.job_cv_id 
WHERE job_cv_history.status = '11' 
GROUP BY job_cv.jobs_id 

回答

3

它不是子查詢很慢。事實是,你對從外部查詢返回的每一行執行這些子查詢。將這些移動到連接,你應該觀察性能的增加。

SELECT 
    jobs.jobs_id, clients.nome_fantasia, concat_ws(' ', user_profiles.first_name, user_profiles.last_name) as fullname, 
jobs.titulo_vaga, jobs.qtd_vagas, company.name as nome_company, jobs_status.name as  status_name, DATEDIFF(NOW(), jobs.data_abertura) as date_idade, 
qtd.qtd_int, 
fechadas.fechadas 
FROM (jobs) 
JOIN clients ON lients.clients_id=jobs.clients_idJOIN user_profiles ON jobs.consultor_id=user_profiles.user_id 
JOIN jobs_status ON jobs.status=jobs_status.jobs_status_id 
JOIN company ON jobs.company_id=company.company_id 
JOIN (
    SELECT jobs_id, count(jobs_id) AS qtd_int FROM job_cv GROUP BY jobs_id 
) AS qtd ON qtd.jobs_id = jobs.jobs_id 
JOIN (
    SELECT job_cv.user_id, count(distinct job_cv.user_id) AS fechadas 
    FROM job_cv_history 
    JOIN job_cv 
    ON job_cv.job_cv_id = job_cv_history.job_cv_id 
    WHERE job_cv_history.status = '11' 
    GROUP BY job_cv.user_id 
) AS fechadas ON job_cv.jobs_id = jobs.jobs_id 
LIMIT 50 
+1

Tkz ...我想出了這個工作:http://pastebin.com/rzjAW7Sj firts加入qtd是好的...但第二...我只得到fechadas的總數...我需要每個工作的總數..任何ideias請? – Roberto

1

使用聯接而不是子查詢。它顯着提高了MySql中的性能。 嘗試使用LEFT JOIN在你的情況,看看性能是否改善或不

2

您可以嘗試創建這些索引:

ALTER TABLE `job_cv` ADD INDEX `job_cv_cindex` (`job_cv_id` ASC, `jobs_id` ASC, `user_id` ASC); 
ALTER TABLE `job_cv_history` ADD INDEX `job_cv_history_cindex` (`job_cv_id` ASC, `status` ASC); 
+0

@Roberto你試過這些索引嗎? – Karolis

+0

剛剛做過,同一時間。你能解釋爲什麼索引可以提供幫助嗎? – Roberto