2013-10-10 89 views
-2

我知道這個查詢可能有缺陷,但你能告訴我如何使它更好。它給我錯誤。我是初學者,所以請不要粗魯。試圖做一個查詢

查詢是:

SET @start = 0; 

IF @start <= 45 
        (SELECT 
        groups.id AS groupid, 
        count(papers.classes) AS cl, 
        start + cl AS st 
       FROM groups, 
        gpaper, 
        papers 
       WHERE cid = '1' 
        AND sid = '4' 
        AND groups.id = '14' 
        AND gpaper.gid = groups.id 
        AND gpaper.pid = papers.paperid 
       ORDER BY groupname) AS t 

我想從查詢結果中,直到ST等於CL。

錯誤我得到的是:

#1064 - 你在你的SQL語法錯誤;檢查對應於你的MySQL服務器版本正確的語法使用近在行 'IF @啓動< = 45 (SELECT groups.id爲g' 手動1

+1

有什麼錯誤?知道我們必須解決什麼或解釋什麼會更容易。 –

+0

'我想要查詢的結果,直到st等於cl。我知道cl沒有定義。你如何將未定義的東西等同於另一個東西?我認爲如果你能展示一些樣本數據和預期結果會更好。 – Kaf

+0

這將是一個PHP變量。抱歉讓我糾正它。 –

回答

0

這是

IF (whatever = whatever) THEN /*<- then!*/ 
SELECT whatever FROM whatever; /*no parantheses and no alias*/ 
END IF; 

另外請注意,你不能使用這個,如果那麼在一個簡單的查詢的事情,你必須使用它在一個存儲過程或一個函數

0

你似乎只想做同樣的查詢46次,與唯一的區別是你是否加0,1,...,4 5到一個字段。

果真如此的話,也許可以與一個SELECT來完成: -

SELECT Sub1.groupid, Sub1.cl, Sub1.cl + Sub0.iCnt AS st 
FROM 
(
    SELECT units.i + tens.i * 10 AS iCnt 
    FROM (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) units 
    CROSS JOIN (SELECT 0 AS i UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) tens 
    HAVING iCnt BETWEEN 0 AND 45 
) Sub0 
CROSS JOIN 
(
    SELECT groups.id AS groupid, count(papers.classes) AS cl 
    FROM groups 
    INNER JOIN gpaper ON gpaper.gid = groups.id 
    INNER JOIN papers ON gpaper.pid = papers.paperid 
    WHERE cid = '1' 
    AND sid = '4' 
    AND groups.id = '14' 
) Sub1 
ORDER BY Sub0.iCnt, groupname