1

I'm wanting to limit an INSERT with a number of rows of another table like this:

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

The following query:

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

returns a 4

When running the script, the following error apears:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT * FROM c_alianca' at line 4

1
  • you can't use subquery on limit but also, you don't need it. make your limitation on your query. Check my answer. Commented Apr 23, 2012 at 10:50

4 Answers 4

5

Why not just query your criteria and insert those like this?

INSERT INTO pacte (alianca_en_pacte, tipus)
SELECT id_alianca_en_pacte1 ,tipus_pacte1
FROM c_alianca
WHERE tipus_pacte1 IS NOT NULL
Sign up to request clarification or add additional context in comments.

2 Comments

Duh. I was thinking too literally! +1
Thanks, it works perfectly! I think I was racking my brain when it was so simple..
4

MySQL currently doesn't support having a subquery as an argument to LIMIT. You will need to use user variables across two queries:

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;

But as suggested by Nesim Razon, in your example one can avoid using LIMIT entirely:

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

Comments

3

Is this what you're after

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

Comments

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';

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.