2015-05-08 216 views
1

我現在所擁有的一個相當大的SQL查詢:檢查是否在另一個表中存在一個id

SELECT a . * , ap . * , i . * , appstatus . * ,(SELECT SUM(rating)/count(case when rating > 0 then 1 end) AS total_rating FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) AS total_rating, (SELECT count(rating) FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) as count 
       FROM apply AS a, applicant AS ap, interest AS i, application_status AS appstatus, apply_tags as at 
       WHERE a.applicantid = ap.applicantid 
       AND a.applicantid = i.applicantid 
       AND a.application_status_id = appstatus.application_status_id 
       AND a.archive = 'false' 
       AND a.jobid =27 

我需要修改這個讓另一臺也檢查,看看是否在它存在a.applyid或不。

根據我現有的查詢,我想對其進行修改,因此它只會輸出apply_tags表中沒有數據的行。

我不知道最好的方法將其整合到我的查詢中。我應該使用連接嗎?

我基本上希望增加一個與聲明是這樣的:

AND a.applyid NOT EXIST at.applyidat是apply_tags表)

我知道我這樣做不對,但就是那種東西的例子我正在努力。

+0

你真的需要'a。 *,ap。 * , 一世 。 *,appstatus。 *'這些表中的所有列 –

回答

2

對不起,我看你已經選擇一個正確答案。但是你的查詢與完美無關。因此,這裏只爲你一個想法,您的查詢可能是怎麼樣的,如果你想優化它第一天:

SELECT a . * , 
ap . * , 
i . * , 
appstatus . * , 
r.total_rating, 
r.count 
FROM apply AS a 
LEFT JOIN (
    SELECT applyid, 
    SUM(rating)/SUM(IF(rating > 0,1,0)) AS total_rating, 
    SUM(IF(rating > 0,1,0)) as count 
    FROM review 
    GROUP BY applyid) AS r 
ON r.applyid=a.applyid 
LEFT JOIN applicant AS ap 
ON a.applicantid = ap.applicantid 
LEFT JOIN interest AS i 
ON a.applicantid = i.applicantid 
LEFT JOIN application_status AS appstatus 
ON a.application_status_id = appstatus.application_status_id 
LEFT JOIN apply_tags as at 
ON a.applyid = at.applyid 
WHERE a.archive = 'false' 
    AND a.jobid =27 
    AND at.applicantid IS NULL 

小說明在原來的查詢,你做這樣的事情:

SELECT a . * , 
..., 
(SELECT SUM(rating)/count(case when rating > 0 then 1 end) AS total_rating FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) AS total_rating, 
(SELECT count(rating) FROM review AS r WHERE r.applyid=a.applyid GROUP BY applyid) as count 
.... 

你問這個技術有什麼問題?所以問題在於MySQL會嘗試從a.table接收到的每條記錄上執行這2 SELECT。與我的LEFT JOIN相反,這將只需要一次所有記錄。如果你在a有100條記錄,MySQL會調用你的子查詢100x2 = 200倍,並且只有1個我的子查詢。

WHERE a.applicantid = i.applicantidLEFT JOIN i ON a.applicantid = i.applicantid幾乎相同的原因。最後一個由MySQL絕對優化。第一個是非常緩慢和沉重。如果你忽略了MySQL的特性,那麼它就是爲它而發明的。你可以從所有5個表中將SELECT *轉換爲php數組,並執行php端的所有邏輯。

你可以只是谷歌一點。例如:https://stackoverflow.com/a/2242015/4421474

+0

我只是好奇爲什麼要改變連接?它比使用正常的AND更快嗎? – ComputerLocus

+0

正常的ANDs ??? :-)我只是沒有語言:-)我沒有改變任何'AND'到'JOIN'。然後用一些解釋檢查更新的答案。 – Alex

+0

我收到以下SQL錯誤與此查詢:'您的SQL語法中有錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在第8行'LEFT JOIN(SELECT applyid,SUM(rating)/'附近使用正確的語法。'r.count'後面有一個逗號,我不我認爲應該在那裏,所以我刪除了這一點,並且是'SUM(IF(rating> 0,1,0)'作爲計數'應該在評分結束時有另一個括號> 0,1,0)部分? – ComputerLocus

相關問題