1

我想用另一个表的行数来限制 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

4 回答 4

5

为什么不只查询您的条件并插入这样的条件?

INSERT INTO pacte (alianca_en_pacte, tipus)
SELECT id_alianca_en_pacte1 ,tipus_pacte1
FROM c_alianca
WHERE tipus_pacte1 IS NOT NULL
于 2012-04-23T10:48:13.033 回答
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;

正如 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;
于 2012-04-23T10:47:55.730 回答
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
于 2012-04-23T10:43:33.257 回答
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';
于 2016-06-16T08:00:19.847 回答