Wednesday, January 23, 2013

MySQL - UPDATE query with LIMIT

Create a New Table .Table name is employee.

Query:

CREATE TABLE `testing`.`employee` (
`id` INT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 255 ) NOT NULL ,
`dept` VARCHAR( 255 ) NOT NULL ,
`salary` DOUBLE NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci;


Insert the 6 rows:

Query:


INSERT INTO `testing`.`employee` (`id`, `name`, `dept`, `salary`) VALUES (NULL, 'peter', 'dept-A', '4000'), (NULL, 'prince', 'dept-A', '5000');
INSERT INTO `testing`.`employee` (`id`, `name`, `dept`, `salary`) VALUES (NULL, 'palani', 'dept-A', '4000'), (NULL, 'raja', 'dept-A', '5000');
INSERT INTO `testing`.`employee` (`id`, `name`, `dept`, `salary`) VALUES (NULL, 'nagaraj', 'dept-A', '8000'), (NULL, 'vasanth', 'dept-A', '10000');

Query: SELECT * FROM `employee`;

Result:

id     name      dept           salary
----------------------------------------
1     peter      dept-A         4000
2     prince      dept-A         5000
3     palani      dept-A         4000
4     raja      dept-A         5000
5     nagaraj  dept-A         8000
6     vasanth  dept-A         10000


Query: SELECT dept , count(dept) FROM `employee` group by dept;

Result:

dept     count(dept)
-----------------------
dept-A    6


I want to change the last 3 rows dept field values from 'dept-A'  to 'dept-B'.

Use following query.This query implement limit option in update query.

Query :
UPDATE employee as a , (SELECT id,dept FROM `employee` where dept='dept-A' limit 3,3) as b SET a.dept='dept-B'  where a.id=b.id;

After run this query  see the all results using below query.


Query: SELECT * FROM `employee`;


Result:
id     name      dept           salary
----------------------------------------
1     peter      dept-A         4000
2     prince      dept-A         5000
3     palani      dept-A         4000
4     raja      dept-B         5000
5     nagaraj  dept-B         8000
6     vasanth  dept-B         10000


Query : SELECT dept , count(dept) FROM `employee` group by dept;

Result:

dept     count(dept)
-----------------------
dept-A    3
dept-B    3

No comments:

Post a Comment