在SQL中使用SELECT COUNT查询LIMIT

时间:2012-04-23 10:41:00

标签: mysql sql phpmyadmin

我想要将INSERT限制为另一个表的行数,如下所示:

INSERT INTO pacte (alianca_en_pacte, tipus)
SELECT id_alianca_en_pacte1 ,tipus_pacte1
FROM c_alianca
LIMIT 0, SELECT COUNT(tipus_pacte1) FROM c_alianca WHERE tipus_pacte1 IS NOT NULL

以下查询:

SELECT COUNT(tipus_pacte1) FROM c_alianca WHERE tipus_pacte1 IS NOT NULL

返回 4

运行脚本时,出现以下错误:

  

您的SQL语法有错误;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   在第4行'SELECT * FROM c_alianca'附近

4 个答案:

答案 0 :(得分:5)

为什么不只是查询您的标准并插入这样的标准?

INSERT INTO pacte (alianca_en_pacte, tipus)
SELECT id_alianca_en_pacte1 ,tipus_pacte1
FROM c_alianca
WHERE tipus_pacte1 IS NOT NULL

答案 1 :(得分:4)

MySQL目前不支持将子查询作为LIMIT的参数。您需要在两个查询中使用用户变量:

SET @limit = (
    SELECT COUNT(tipus_pacte1) FROM c_alianca WHERE tipus_pacte1 IS NOT NULL
);

INSERT INTO pacte (alianca_en_pacte, tipus)
    SELECT id_alianca_en_pacte1 ,tipus_pacte1
    FROM c_alianca
    LIMIT 0, @limit;

as suggested by Nesim Razon,在您的示例中,可以完全避免使用LIMIT

INSERT INTO pacte (alianca_en_pacte, tipus)
    SELECT id_alianca_en_pacte1 ,tipus_pacte1
    FROM c_alianca
    WHERE tipus_pacte1 IS NOT NULL;

答案 2 :(得分:3)

这就是你追求的目标

INSERT INTO pacte (alianca_en_pacte, tipus)
SELECT id_alianca_en_pacte1, tipus_pacte1, 
    ( SELECT COUNT(tipus_pacte1) FROM c_alianca WHERE tipus_pacte1 IS NOT NULL ) AS tipus 
FROM c_alianca LIMIT 0

答案 3 :(得分:0)

below is the code for Limitation on ID....It is the example for you
Declare @Counter int 
Set @Counter=(SELECT Count(Student_ID) as 'StudentCount' FROM CourseSemOne 
where Student_ID=1 Having Count(Student_ID) < 6 and Count(Student_ID) > 0)
if(@Counter <6)
print'Sorry! You cannot add more than five subject data for a single student'
else
print'Insert Code';