1. 程式人生 > 其它 >【SQL基礎】基礎查詢:所有列、指定列、去重、限制行數、改名

【SQL基礎】基礎查詢:所有列、指定列、去重、限制行數、改名

〇、建表資料

drop table if exists user_profile;
CREATE TABLE `user_profile` (
`id` int NOT NULL,
`device_id` int NOT NULL,
`gender` varchar(14) NOT NULL,
`age` int ,
`university` varchar(32) NOT NULL,
`province` varchar(32)  NOT NULL);
INSERT INTO user_profile VALUES(1,2138,'male',21,'北京大學','BeiJing');
INSERT
INTO user_profile VALUES(2,3214,'male',null,'復旦大學','Shanghai'); INSERT INTO user_profile VALUES(3,6543,'female',20,'北京大學','BeiJing'); INSERT INTO user_profile VALUES(4,2315,'female',23,'浙江大學','ZheJiang'); INSERT INTO user_profile VALUES(5,5432,'male',25,'山東大學','Shandong');

一、基礎查詢

1、查詢所有列

注意:不要用*,而是寫全部列名

select 
    id, device_id,
    gender, age,
    university, province
from user_profile;

2、查詢指定列

二、簡單處理查詢結果

3、查詢結果去重

select 
    DISTINCT university
from user_profile;

注意:DISTINCT是去重關鍵字

4、查詢結果限制返回行數

前n個:SQL的最後加LIMIT n

查詢前2個使用者的明細裝置id

select
    device_id
from user_profile
LIMIT 2;

5、將查詢後的列重新命名

select
    device_id as user_infos_example
from user_profile
LIMIT 2;