-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 服务器版本相对应的手册,以在第 1 行的 'IF @start <= 45 (SELECT groups.id AS g' 附近使用正确的语法

4

2 回答 2

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
于 2013-10-11T08:49:05.167 回答
0

它是

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

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

于 2013-10-10T13:53:11.017 回答