Created
January 4, 2016 18:28
-
-
Save korniychuk/ddef6bbeb4bebb6efe40 to your computer and use it in GitHub Desktop.
count & having example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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` ) | |
Обновить записи по тому же условию можно так
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
Вот еще способ. Этот лучше. Будет быстрее работать и проще для понимания.