12-MySQL-Ubuntu-數據表的查詢-數據准備和基本查詢(一)


一,數據准備

創建數據庫、數據表


-- 創建數據庫
create database python_test_1 charset=utf8;

-- 使用數據庫
use python_test_1;

-- students表
create table students(
    id int unsigned primary key auto_increment not null,
    name varchar(20) default '',
    age tinyint unsigned default 0,
    height decimal(5,2),
    gender enum('男','女','中性','保密') default '保密',
    cls_id int unsigned default 0,
    is_delete bit default 0
);

-- classes表
create table classes (
    id int unsigned auto_increment primary key not null,
    name varchar(30) not null
);

准備數據

-- 向students表中插入數據
insert into students values
(0,'小明',18,180.00,2,1,0),
(0,'小月月',18,180.00,2,2,1),
(0,'彭於晏',29,185.00,1,1,0),
(0,'劉德華',59,175.00,1,2,1),
(0,'黃蓉',38,160.00,2,1,0),
(0,'鳳姐',28,150.00,4,2,1),
(0,'王祖賢',18,172.00,2,1,1),
(0,'周傑倫',36,NULL,1,1,0),
(0,'程坤',27,181.00,1,2,0),
(0,'劉亦菲',25,166.00,2,2,0),
(0,'金星',33,162.00,3,3,1),
(0,'靜香',12,180.00,2,4,0),
(0,'郭靖',12,170.00,1,4,0),
(0,'周傑',34,176.00,2,5,0);

-- 向classes表中插入數據
insert into classes values (0, "python_01期"), (0, "python_02期");

 

二,基本查詢

(1)查詢所有字段

select * from 表名;

 

(2)查詢指定字段

select 字段1,字段2,... from 表名;

 

(3)查詢時使用as給字段起別名

select 字段1 as 別名1,字段2 as 別名2,... from 表名;

 

(4)查詢時使用as給表起別名

select 別名.字段1,別名.字段2,... from 表名 as 別名;

注:一旦使用別名,sql語句總就不能再使用原來的表名.下面給出實例:

例:

(錯誤的SQL語句)select 表名.字段1,別名.字段2,... from 表名 as 別名;

(正確的SQL語句)select 別名.字段1,別名.字段2,... from 表名 as 別名;

 

(5)查詢時使用distinct去除重復字段

select dintinct 字段 from 表名;

例:

查詢gender字段的種類數,使用distinct去重查看


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM