-1

I'm trying to get the number of rows in a table, and then insert that number into that same table, all with a single query. I looked at subquery and it throws error since I'm doing it on the same table.

Then I looked at variables and it works but mySQL still throws an error about empty result.

SET @nums := (SELECT COUNT(*) FROM myitems);
INSERT INTO myitems ( `label`, `counted`) VALUES ('blah', @nums);

Can I trust this will be robust? I'm not super expert on SQL statements.

PS: I know about AUTO_INCREMENT which you might think should be utilized here. I simplified my situation to keep the question esy to digest (and hopefully answer).

4

1 回答 1

0

为什么不使用INSERT ... SELECT

INSERT INTO myitems( `label`, `counted`)
SELECT 'blah', COUNT(*) FROM myitems;

我不知道你为什么要这样做,但它确实回答了你的问题

于 2013-11-13T03:38:27.583 回答