试图进行查询

时间:2013-10-10 10:57:36

标签: mysql sql select if-statement

我知道这个查询可能有缺陷,但你能告诉我如何让它变得更好。它给了我错误。我是初学者,所以请不要粗鲁。

查询是:

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 @start&lt; = 45附近使用正确的语法                      (选择                      groups.id AS g'在第1行

2 个答案:

答案 0 :(得分:0)

这是

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

另请注意,如果在简单查询中不能使用它,则必须在存储过程或函数中使用它。

答案 1 :(得分:0)

您似乎只想进行46次相同的查询,唯一的区别是您是否将0,1,....,45添加到字段中。

如果是这样,可以用一个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