SELECT DISTINCTstate, cityFROM customersWHEREstateIS NOT NULLORDER BYstate , city;
执行上面查询,得到以下结果 -
mysql>SELECT DISTINCTstate, city FROM customers WHEREstateIS NOT NULLORDER BYstate ,city;+---------------+----------------+| state | city |+---------------+----------------+| BC | Tsawassen || BC | Vancouver || CA | Brisbane || CA | Burbank || CA | Burlingame || CA | Glendale || CA | Los Angeles || CA | Pasadena || CA | San Diego || CA | San Francisco || CA | San Jose || CA | San Rafael || Co. Cork | Cork || CT | Bridgewater || CT | Glendale || CT | New Haven || Isle of Wight | Cowes || MA | Boston || MA | Brickhaven || MA | Cambridge || MA | New Bedford || NH | Nashua || NJ | Newark || NSW | Chatswood || NSW | North Sydney || NV | Las Vegas || NY | NYC || NY | White Plains || Osaka | Kita-ku || PA | Allentown || PA | Philadelphia || Pretoria | Hatfield || Qubec | Montral || Queensland | South Brisbane || Tokyo | Minato-ku || Victoria | Glen Waverly || Victoria | Melbourne |+---------------+----------------+37rowsinset
没有DISTINCT子句,将查询获得州(state)和城市(city)的重复组合如下:
SELECTstate, cityFROM customersWHEREstateIS NOT NULLORDER BYstate, city;
mysql>SELECTstateFROM customers GROUP BYstate;+---------------+| state |+---------------+| NULL || BC || CA || Co. Cork || CT || Isle of Wight || MA || NH || NJ || NSW || NV || NY || Osaka || PA || Pretoria || Qubec || Queensland || Tokyo || Victoria |+---------------+19rowsinset
可以通过使用DISTINCT子句来实现类似的结果:
mysql>SELECT DISTINCTstateFROM customers;+---------------+| state |+---------------+| NULL || NV || Victoria || CA || NY || PA || CT || MA || Osaka || BC || Qubec || Isle of Wight || NSW || NJ || Queensland || Co. Cork || Pretoria || NH || Tokyo |+---------------+19rowsinset
mysql>SELECT DISTINCTstateFROM customers ORDER BYstate;+---------------+| state |+---------------+| NULL || BC || CA || Co. Cork || CT || Isle of Wight || MA || NH || NJ || NSW || NV || NY || Osaka || PA || Pretoria || Qubec || Queensland || Tokyo || Victoria |+---------------+19rowsinset
SELECTCOUNT(DISTINCTstate)FROM customersWHERE country ='USA';
执行上面查询,得到以下结果 -
mysql>SELECTCOUNT(DISTINCTstate) FROM customers WHERE country ='USA';+-----------------------+| COUNT(DISTINCTstate) |+-----------------------+| 8 |+-----------------------+1rowinset