English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Possiamo utilizzare contemporaneamente DISTINCT e COUNT in una query MySQL. Prima di tutto, creiamo una tabella. Il comando CREATE viene utilizzato per creare una tabella.
mysql> creare tabella DistCountDemo - > ( - > id int, - > name varchar(100), - > age int - > );
Inserire record con l'aiuto del comando INSERT.
mysql> insert into DistCountDemo values(1,'John',23); mysql> insert into DistCountDemo values(2,'Bob',24); mysql> insert into DistCountDemo values(3,'John',23); mysql> insert into DistCountDemo values(4,'Carol',23);
Visualizzare tutti i record con l'aiuto della statement SELECT.
mysql> select * from DistCountDemo;
Di seguito è riportato l'output.
+------+-------+------+ | id | name | age | +------+-------+------+ | 1 | John | 23 | | 2 | Bob | 24 | | 3 | John | 23 | | 4 | Carol | 23 | +------+-------+------+ 4 rows in set (0.00 sec)
Utilizzare COUNT e DISTINCT per trovare il numero di studenti di 23 anni.
mysql> SELECT COUNT(DISTINCT name) FROM DistCountDemo WHERE age=23;
Di seguito è riportato l'output.
+----------------------+ | COUNT(DISTINCT name) | +----------------------+ | 2 | +----------------------+ 1 row in set (0.05 sec)