Skip to content

Instantly share code, notes, and snippets.

@korniychuk
Created January 4, 2016 18:28
Show Gist options
  • Save korniychuk/ddef6bbeb4bebb6efe40 to your computer and use it in GitHub Desktop.
Save korniychuk/ddef6bbeb4bebb6efe40 to your computer and use it in GitHub Desktop.
count & having example
DROP TABLE IF EXISTS `user`;
DROP TABLE IF EXISTS `video`;
CREATE TABLE IF NOT EXISTS `user` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255),
`access` TINYINT UNSIGNED,
PRIMARY KEY `pk_id`(`id`)
) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS `video` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255),
PRIMARY KEY `pk_id`(`id`)
) ENGINE = InnoDB;
INSERT INTO `user`(`name`, `access`) VALUES
('Berry Pettrey', 4),
('Scarlet Collicott', 2),
('Bulah Kamens', 1),
('Tressie Bagnaschi', 5)
;
INSERT INTO `video`(`name`) VALUES
('Long Creedon'),
('Kenneth Schoninger'),
('Valeri Jorski')
;
SELECT
`u`.*, COUNT(*) AS `video_count`
FROM `user` AS `u`, `video` AS `v`
GROUP BY `u`.`id`
HAVING ( `u`.`access` < `video_count` )
@korniychuk
Copy link
Author

Обновить записи по тому же условию можно так

UPDATE
    `user` AS `u`,
    (SELECT COUNT(*) AS `count` FROM `video`) AS `v`
SET
  `u`.`access` = `u`.`access`+1
WHERE ( `u`.`access` < `v`.`count` );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment