Related
I am using Laravel 4.2 and have a query:
DB::table('data')->whereIn('t_id', $new_ids);
->whereNotIn('l_id', $old_ids);
->groupBy('l_id')->update(array('t_id' => $new_t_id));
This causes an error:
500 - SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1569648-7302' for key 'data_l_id_t_id_unique' (SQL: update `data` set `t_id` = 7302 where `t_id` in (4772, 4860, 4861, 5653, 6396, 6743) and `l_id` not in (2994190)) # /
The problems seems to be with groupBy() clause which is not being executed, thus making duplicate l_id to be pulled into the query:
mysql> select l_id from data where t_id=7302;
+---------+
| l_id |
+---------+
| 2994190 |
+---------+
1 row in set (0.00 sec)
mysql> select l_id from data where t_id in (4772, 4860, 4861, 5653, 6396, 6743);
+---------+
| l_id |
+---------+
| 1569648 |
| 1593870 |
| 1594096 |
| 1628872 |
| 1569648 |
| 1593870 |
| 1594096 |
| 1628872 |
| 1569648 |
| 1593870 |
| 1594096 |
| 1628872 |
| 1879092 |
| 2283518 |
| 2284586 |
| 2604466 |
+---------+
16 rows in set (0.00 sec)
mysql> select l_id from data where t_id in (4772, 4860, 4861, 5653, 6396, 6743) GROUP BY l_id;
+---------+
| l_id |
+---------+
| 1569648 |
| 1593870 |
| 1594096 |
| 1628872 |
| 1879092 |
| 2283518 |
| 2284586 |
| 2604466 |
+---------+
8 rows in set (0.00 sec)
Schema:
mysql> show create table data;
CREATE TABLE `data` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`l_id` bigint(20) unsigned NOT NULL,
`t_id` bigint(20) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `data_l_id_tag_id_unique` (`l_id`,`t_id`),
KEY `data_t_id_foreign` (`t_id`),
CONSTRAINT `data_l_id_foreign` FOREIGN KEY (`l_id`) REFERENCES `lis` (`id`),
CONSTRAINT `data_t_id_foreign` FOREIGN KEY (`t_id`) REFERENCES `tas` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4544794 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci
Basically I need to update t_id for certain l_ids but still ensure no duplicate t_id/l_id happen. I could do this by looping through each t_id and checking for duplicates before updating but thought a shortcut via groupBy() would be a better way of doing it.
Is it possible to make Laravel do a groupBy() while updating? More generally can an update be executed while checking for duplicates, even in plain SQL?
Edit: Separating update from group by
Making UPDATE and GROUP BY seperate helps resolve GROUP BY problem but not duplicate problem:
$required_l_ids = DB::table('data')->whereIn('t_id', $new_ids);
->whereNotIn('l_id', $old_ids);
->groupBy('l_id')->lists('l_id');
if ( !empty($required_l_ids) ) {
DB::table('data')->whereIn('l_id', $required_l_ids)->whereIn('t_id', $new_ids)->update(array('t_id' => $new_tag_id));
}
Still gives an error:
500 - SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '1593870-7302' for key 'data_l_id_t_id_unique' (SQL: update `data` set `t_id` = 7302 where `l_id` in (1593870, 1594096, 1628872, 1879092, 2283518, 2284586, 2604466) and `t_id` in (4772, 4860, 4861, 5653, 6396, 6743)) # /
Edit 2: Sample data
CREATE TABLE `data` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`l_id` bigint(20) unsigned NOT NULL,
`t_id` bigint(20) unsigned NOT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `data_l_id_t_id_unique` (`l_id`,`t_id`)
) ENGINE=InnoDB AUTO_INCREMENT=4544794 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
INSERT into data (l_id, t_id) VALUES (1569648,7302);
INSERT into data (l_id, t_id) VALUES (2994190,7302);
INSERT into data (l_id, t_id) VALUES (1593870,4772);
INSERT into data (l_id, t_id) VALUES (1594096,4772);
INSERT into data (l_id, t_id) VALUES (1628872,4772);
INSERT into data (l_id, t_id) VALUES (1569648,4860);
INSERT into data (l_id, t_id) VALUES (1593870,4860);
INSERT into data (l_id, t_id) VALUES (1594096,4860);
INSERT into data (l_id, t_id) VALUES (1628872,4860);
INSERT into data (l_id, t_id) VALUES (1569648,4861);
INSERT into data (l_id, t_id) VALUES (1593870,4861);
INSERT into data (l_id, t_id) VALUES (1594096,4861);
INSERT into data (l_id, t_id) VALUES (1628872,4861);
INSERT into data (l_id, t_id) VALUES (1879092,5653);
INSERT into data (l_id, t_id) VALUES (2283518,6396);
INSERT into data (l_id, t_id) VALUES (2284586,6396);
INSERT into data (l_id, t_id) VALUES (2604466,6743);
UPDATE data AS d1 LEFT JOIN data AS d2 ON d1.l_id = d2.l_id AND d2.t_id = 7302 SET d1.t_id = 7302 WHERE d1.t_id IN (4772,4860,4861,5653,6396,6743) AND d1.l_id NOT IN (1569648,2994190) AND d2.l_id IS NULL;
sqlfiddle: http://sqlfiddle.com/#!9/e9a50
Error: Duplicate entry '1593870-7302' for key 'data_l_id_t_id_unique'
I don't know the Laravel syntax, but I think this is the MySQL syntax for what you want:
UPDATE data AS d1
JOIN (SELECT l_id, MIN(t_id) AS min_t_id
FROM data
WHERE d1.t_id IN ($new_ids)
AND d1.l_id NOT IN ($old_ids)
GROUP BY l_id) AS d3 ON d1.l_id = d3.l_id AND d1.t_id = d3.min_t_id
LEFT JOIN data AS d2 ON d1.l_id = d2.l_id AND d2.t_id = $new_tag_id
SET d1.t_id = $new_tag_id
WHERE d2.l_id IS NULL
This combines an UPDATE with the LEFT JOIN/NULL pattern in Return row only if value doesn't exist
The first JOIN makes sure that only one row for each l_id is updated, so you don't create duplicates. It arbitrarily chooses the lowest t_id to replace.
DEMO
I do not know if it's possible at all, but I have two tables, userBasic and carPlateConfidence, in carPlateConfidence I would like to insert id of userBasic where emails are matched.
$query .= "INSERT IGNORE INTO userBasic (id_uM, userNameG, userEmailG) values ((SELECT id_uM FROM userMore WHERE userEmailG='$userEmailG'),'$userNameG', '$userEmailG');";
$query .= "INSERT IGNORE INTO carPlateConfidence (emailConfid, id_uB,plateNumber, confidencePlate, plateNumberUn) values ('$userEmailG', (SELECT id_uB FROM userBasic WHERE userEmailG='(SELECT max(emailConfid) FROM carPlateConfidence)'), '$plateNumber','$confidencePlate', '$plateNumberUn');";
So if I have:
userBasic:
id_uM = 555;
userNameG = BlaBla;
userEmailG = blabla#blabla.com
And in this table I would like
carPlateConfidence:
emailConfid = blabla#blabla.com;
id_uB = 555
plateNumber = 1111
confidencePlate = 70
plateNumberUn = 2222
AND if email do not matched:
emailConfid = blabla2#blabla.com;
id_uB = NULL
plateNumber = 1111
confidencePlate = 70
plateNumberUn = 222
P>S> Currently I have tried this, to select id from userBasic:
(SELECT id_uB FROM userBasic WHERE userEmailG='(SELECT max(emailConfid) FROM carPlateConfidence)')
id_uB in carPlateConfidence is set as foreign key;
Tables:
--
-- Table structure for table `carPlateConfidence`
--
DROP TABLE IF EXISTS `carPlateConfidence`;
CREATE TABLE IF NOT EXISTS `carPlateConfidence` (
`id_cof` int(11) NOT NULL AUTO_INCREMENT,
`id_uB` int(11) NOT NULL,
`emailConfid` varchar(50) NOT NULL,
`plateNumber` varchar(10) NOT NULL,
`confidencePlate` varchar(10) DEFAULT NULL,
`plateNumberUn` varchar(10) DEFAULT NULL,
PRIMARY KEY (`id_cof`),
KEY `id_uB` (`id_uB`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
-- --------------------------------------------------------
--
-- Table structure for table `userBasic`
--
DROP TABLE IF EXISTS `userBasic`;
CREATE TABLE IF NOT EXISTS `userBasic` (
`id_uB` int(11) NOT NULL AUTO_INCREMENT,
`id_uM` int(11) NOT NULL,
`userNameG` varchar(50) NOT NULL,
`userEmailG` varchar(50) NOT NULL,
PRIMARY KEY (`id_uB`),
UNIQUE KEY `userEmailG` (`userEmailG`),
KEY `id_uM` (`id_uM`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=119 ;
--
-- Constraints for dumped tables
--
--
-- Constraints for table `carPlateConfidence`
--
ALTER TABLE `carPlateConfidence`
ADD CONSTRAINT `carPlateConfidence_ibfk_1` FOREIGN KEY (`id_uB`) REFERENCES `userBasic` (`id_uB`);
--
-- Constraints for table `userBasic`
--
ALTER TABLE `userBasic`
ADD CONSTRAINT `userBasic_ibfk_1` FOREIGN KEY (`id_uM`) REFERENCES `userMore` (`id_uM`);
So you want an update, not an insert :
UPDATE carPlateConfidence t
SET t.id_uB = (SELECT distinct s.id_uM FROM userBasic s
WHERE s.userEmailG = t.emailConfid)
This will work only if there can be only 1 match, if there can be more then one match you should specify which one you want, if it doesn't matter, either use MAX() or limit :
UPDATE carPlateConfidence t
SET t.id_uB = (SELECT max(s.id_uM) FROM userBasic s
WHERE s.userEmailG = t.emailConfid)
My MySQL app allows users to create bookmarks and organize them with tags.
A tag is added to a bookmark with a middle MySQL DB table bookmark_tag_relationship
I would like to add a Foreign Key to auto-delete all records in bookmark_tag_relationship when a Bookmarks record is deleted.
All the bookmark_tag_relationship records deleted would have a bookmark_id column that matches the id column on the bookmark record that is deleted
How can I set this up correctly based on the 3 table structures shown below?
Failed attempt #1
I tried something like this:
ALTER TABLE bookmarks ADD FOREIGN KEY (`id`)
REFERENCES bookmark_tag_relationship(`bookmark_id`);
It returned an error with no information just that it could not create it.
table bookmarks
--
-- Table structure for table `bookmarks`
--
CREATE TABLE IF NOT EXISTS `bookmarks` (
`id` int(20) NOT NULL,
`url_id` int(20) DEFAULT NULL,
`user_id` int(30) DEFAULT NULL,
`name` varchar(255) DEFAULT NULL,
`url` varchar(255) DEFAULT NULL,
`favicon_url` varchar(255) DEFAULT NULL,
`project_url` varchar(255) DEFAULT NULL,
`github_url` varchar(255) DEFAULT NULL,
`demo_url` int(255) DEFAULT NULL,
`local_demo_url` varchar(255) DEFAULT NULL,
`image1` varchar(255) DEFAULT NULL,
`image2` varchar(255) DEFAULT NULL,
`image3` varchar(255) DEFAULT NULL,
`image4` varchar(255) DEFAULT NULL,
`description` text,
`notes` text,
`tags_string` varchar(255) DEFAULT NULL,
`click_count` int(10) NOT NULL DEFAULT '0',
`tag_count` int(10) NOT NULL DEFAULT '0',
`created_on` datetime DEFAULT NULL,
`updated_on` datetime DEFAULT NULL,
`last_viewed_on` datetime DEFAULT NULL,
`active` int(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
table tags
--
-- Table structure for table `tags`
--
CREATE TABLE IF NOT EXISTS `tags` (
`id` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`name` varchar(100) DEFAULT NULL,
`description` text,
`color` varchar(10) DEFAULT NULL,
`bookmark_count` int(11) NOT NULL DEFAULT '0',
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
table bookmark_tag_relationship
--
-- Table structure for table `bookmark_tag_relationship`
--
CREATE TABLE IF NOT EXISTS `bookmark_tag_relationship` (
`id` int(11) NOT NULL,
`bookmark_id` int(30) NOT NULL,
`tag_id` int(30) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
Three issues:
You have not defined a primary key in the table bookmarks (or any other);
In comments you clarified you actually have them, so then this is a non-issue;
You have the foreign key constraint defined in the opposite direction. You should define it on the child table;
You need to add the ON DELETE CASCADE clause.
So, execute this, and it will work (you can skip the first one, since in comments you clarified you already have the primary key):
ALTER TABLE bookmarks ADD
CONSTRAINT PRIMARY KEY(id);
ALTER TABLE bookmark_tag_relationship
ADD FOREIGN KEY (bookmark_id)
REFERENCES bookmarks(id)
ON DELETE CASCADE;
Now you can delete a bookmark, for example:
DELETE FROM bookmarks WHERE id = 1;
...and the related records in bookmark_tag_relationship will be deleted in the same transaction.
Some additional remarks:
The difference between int(20) and int(30) that you have for the primary key and foreign key types cannot be very useful. It does not influence the constraint, but I would still suggest to harmonise that as follows:
ALTER TABLE bookmark_tag_relationship
MODIFY bookmark_id int(20) NOT NULL;
It is not needed to surround your table and column names with backticks. Only when you have chosen reserved words for those names, they are needed, but that is something you'd want to avoid anyway.
EDIT: You're foreign key is also failing because you do not have a primary key. A foreign key is a reference to a primary key.
I would setup a trigger for bookmarks on delete.
DELIMITER $$
CREATE DEFINER=`username`#`%` TRIGGER `bookmarks_ADEL` AFTER DELETE ON `bookmarks` FOR EACH ROW
BEGIN
DELETE FROM bookmark_tag_relationship WHERE bookmark_id = old.id;
END
When a row from Bookmarks is deleted, it will take that ID and remove the row out of bookmark_tag_relationship.
You need to set Primary keys in both those tables, most likely the ID
One note about using a cascade delete on foreign key. It will not activate any triggers that are set on those deleted rows. So as you progress, if you decide to trigger off them to remove or modify more information, the foreign key cascade will not activate them and you'll have to trigger on delete anyway.
Try to add a ON DELETE CASCADE on your foreign key.
ALTER TABLE bookmark_tag_relationship ADD FOREIGN KEY (`bookmark_id`)
REFERENCES bookmarks(`id`)
ON DELETE CASCADE;
There's a few reasons why your foreign key is not working.
First of all, you need to make sure the column id of each table is a primary key.
ALTER TABLE table_name
ADD PRIMARY KEY (table_column)
After you've added your primary key, you need to make sure that their type is the same.
In your bookmark_tag_relationship table, the bookmark_id is INT(30), but in your bookmarks* table, your column 'id' is **INT(20). You need to make sure both of them are the same. So either change the id from bookmarks to INT(30) or change the other one to INT(20).
And at last, your foreign key query is reversed. You want it the other way around.
ALTER TABLE bookmark_tag_relationship ADD FOREIGN KEY (`bookmark_id`)
REFERENCES bookmarks(`id`)
ON DELETE CASCADE;
You want the bookmark_tag_relationship to be deleted when a bookmark is deleted, and not the other way around.
Use a primary auto incremented key on the id columns. And then like others said use cascade on delete with foreign keys.
mysql> show create table bookmarks\G
*************************** 1. row ***************************
Table: bookmarks
Create Table: CREATE TABLE `bookmarks` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
mysql> show create table tags\G
*************************** 1. row ***************************
Table: tags
Create Table: CREATE TABLE `tags` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
mysql> show create table bookmarks_tags\G
*************************** 1. row ***************************
Table: bookmarks_tags
Create Table: CREATE TABLE `bookmarks_tags` (
`bookmark_id` int(11) NOT NULL DEFAULT '0',
`tag_id` int(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`bookmark_id`,`tag_id`),
CONSTRAINT `bookmarks_tags_ibfk_1` FOREIGN KEY (`bookmark_id`) REFERENCES `bookmarks` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
1 row in set (0.01 sec)
mysql> select * from bookmarks;
+----+-----------+
| id | title |
+----+-----------+
| 1 | bookmark1 |
| 2 | bookmark2 |
| 3 | bookmark3 |
+----+-----------+
3 rows in set (0.00 sec)
mysql> select * from tags;
+----+------+
| id | name |
+----+------+
| 1 | tag1 |
| 2 | tag2 |
| 3 | tag3 |
| 4 | tag4 |
| 5 | tag5 |
+----+------+
5 rows in set (0.00 sec)
mysql> select * from bookmarks_tags;
+-------------+--------+
| bookmark_id | tag_id |
+-------------+--------+
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 2 | 1 |
| 2 | 4 |
| 3 | 5 |
+-------------+--------+
6 rows in set (0.00 sec)
mysql> delete from bookmarks where title = 'bookmark1';
Query OK, 1 row affected (0.01 sec)
mysql> select * from bookmarks; select * from tags; select * from bookmarks_tags;
+----+-----------+
| id | title |
+----+-----------+
| 2 | bookmark2 |
| 3 | bookmark3 |
+----+-----------+
2 rows in set (0.00 sec)
+----+------+
| id | name |
+----+------+
| 1 | tag1 |
| 2 | tag2 |
| 3 | tag3 |
| 4 | tag4 |
| 5 | tag5 |
+----+------+
5 rows in set (0.01 sec)
+-------------+--------+
| bookmark_id | tag_id |
+-------------+--------+
| 2 | 1 |
| 2 | 4 |
| 3 | 5 |
+-------------+--------+
3 rows in set (0.00 sec)
after going through many attempts, i finally can display data from child table. I have 2 tables, user (parent) and useradvert(child).
user
-id (pk)
-name
-username
-telno
useradvert
-id(index)
etc.........
it's a 1 to many relation. from table users to table useradvert. table users suppose to pull many rows from table useradvert based on specific id which matches id in table users. But, instead it only display first row from useradvert. No matter how you login with different username, you will always see the first row from useradvert and not the rows that is supposed to display. For ur info, I'm a newbie. Any help is appreciated. tqs.
below is extract;
$query = "SELECT * FROM users,useradvert WHERE users.id=useradvert.id";
$stmt = $conn->prepare($query);
$stmt->execute();
$res = $stmt->get_result();
$row2 = $res->fetch_array();
$_SESSION['name2'] = $row2['name2'];
$_SESSION['color2'] = $row2['color2'];
$_SESSION['hobby2'] = $row2['hobby2'];
$_SESSION['radiobtn'] = $row2['radiobtn'];
$_SESSION['kupon'] = $row2['kupon'];
$_SESSION['image'] = $row2['image'];
$_SESSION['image2'] = $row2['image2'];
below is extract -continue on same page
<?php
//display record from table- useradveret -(child table)
// while($row = $res->fetch_array()){
echo $_SESSION['name2']."<br/>";
echo $_SESSION['color2']."<br/>";
echo $_SESSION['hobby2']."<br/>";
echo $_SESSION['radiobtn']."<br/>";
echo $_SESSION['kupon']."<br/>";
echo $_SESSION['image']."<br/>";
echo $_SESSION['image2']."<br/>";
// }
?>
table query for useradvert
-- Table structure for table useradvert
CREATE TABLE IF NOT EXISTS `useradvert` (
`id` int(10) unsigned NOT NULL,
`name2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`color2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`hobby2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`radiobtn` varchar(10) COLLATE utf8_unicode_ci NOT NULL,
`kupon` varchar(20) COLLATE utf8_unicode_ci NOT NULL,
`image` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
`image2` varchar(60) COLLATE utf8_unicode_ci NOT NULL,
KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
--
-- Dumping data for table `useradvert`
--
INSERT INTO `useradvert` (`id`, `name2`, `color2`, `hobby2`, `radiobtn`, `kupon`, `image`, `image2`) VALUES
(97, 'testthree nickname', 'colorthree', 'hobbythree', 'female', '', 'uploads/testpic1.jpg', 'uploads/testpic2.jpg'),
(99, 'testfivenamecick', 'testfivehcolor', 'testfivecolor', 'female', '', 'uploads/testpic3.jpg', 'uploads/testpic4.jpg'),
(97, 'lagitestthree', 'trheecolor', 'threehobby', 'female', '', 'uploads/testpic5.jpg', 'uploads/testpic6.jpg');
--
-- Constraints for dumped tables
--
--
-- Constraints for table `useradvert`
--
ALTER TABLE `useradvert`
ADD CONSTRAINT `useradvert_ibfk_1` FOREIGN KEY (`id`) REFERENCES `users` (`id`);
I guess your sql query is not correct. Yo use the id field of useradvert table, but that is the index field of that table. That looks wrong. You should have a foreign key userId in useradvert table for the join. Then you query should look something like this:
SELECT * FROM users u
INNER JOIN useradvert ua ON u.id = ua.userId
Then you should get all useradvert fields for the user.
The 2 tables should look something like this:
Table user:
id | name | ...
1 | Ben | ...
2 | Markus | ...
Table useradvert:
id | userid | ...
1 | 1 | ...
2 | 1 | ...
userid in useradvert is the foreign key to create the relationship between the 2 tables. Does that make sense?
I don't know how to COUNT a column named id. I tried
mysql_query("INSERT INTO `servers` (`user_id`, `ip`, `port`, `banner`, `disabled`, `vip`,`premium`, `name`, `status`, `votifier_key`, `votifier_port`, `country`)
VALUES ('$session_user_id', '$ip', '$port', 's=.'id'.back', '$disabled', 0,'false', '$name', '1', '$votifier', '$votPort', '$country')");
But it's not working, because I couldn't get id. Can someone help?
You need to use INSERT ... SELECT request.
Suppose, we have an empty table test:
test
|----+-------|
| id | value |
|----+-------|
CREATE TABLE IF NOT EXISTS `test` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`value` int(10) unsigned DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
When we run this SQL request:
INSERT INTO test (value) SELECT COUNT(*) FROM `test`
we shall sequentially get test filling up with data:
| id | value |
|----+-------|
| 1 | 0 |
| 2 | 1 |
| 3 | 2 |
Use this approach for your table, and you'll get what you need.