MySql数据库探路

数据库

  • 数据库的基本操作:

一)、库操作:

1、显示已有的数据库

句法:SHOW DATABASES [LIKE wild]

如果使用LIKE wild部分,wild字符串可以是一个使用SQL%_通配符的字符串。

举例:

显示所有:show databases

显示:show databases LIKE 'test_db';

 

2、创建数据库:

句法:CREATE DATABASE db_name

 

3、删除数据库:

句法:DROP DATABASE [IF EXISTS] db_name

 

4、选择数据库:

句法:USE database_name

 

二)、表操作:

1、查询表:

句法:SHOW TABLES [FROM db_name] [LIKE wild]

 

2、创建表:

句法:CREATE TABLE tbl_name(create_definition,...) [TYPE =table_type]

举例:

CREATE TABLE Persons(Id_P int,LastName varchar(255),FirstName varchar(255),Address varchar(255),City varchar(255))

 

3、修改表结构:

句法:alter db_name 。。。。

1、增加列:给表pet_db增加一列weight,类型为int

alter table pet_db add weight int;

2、删除列:

alter table pet_db drop weight

3、修改列:

alter table pet_db modify weight char

4、给列更名:

alter table pet_db change weight wei;

5、给表更名:

alter table tbl_name rename new_tbl

 

4、删除表:

句法:DROP TABLE [IF EXISTS] tbl_name [, tbl_name,...]

 

三)、记录操作:

1、插入:

句法:INSERT [INTO] tbl_name [(col_name,...)] VALUES (pression,...),…

举例:插入多条:

insert into worker values(‗tom,tom@yahoo.com),(‗paul,paul@yahoo.com);

1、使用INSERT…SELECT语句插入从其他表选择的行

insert into tbl_name1(col1,col2) select col3,col4 from tbl_name2;

2、批量录入:

语法:LOAD DATA [LOCAL] INFILE 'file_name.txt' [REPLACE | IGNORE] INTO TABLE tbl_name

 

2、查询select:

句法:

SELECT selection_list 选择哪些列

FROM table_list 从何处选择行

WHERE primary_constraint 行必须满足什么条件

GROUP BY grouping_columns 怎样对结果分组

HAVING secondary_constraint 行必须满足的第二条件

ORDER BY sorting_columns 怎样对结果排序

LIMIT count 结果限定

举例:

排序(逆序)

SELECT name, species, birth FROM pet ORDER BY species, birth DESC;

按列表排序:

select id,revenue,month from Department order by FIELD(month ,"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");

查询分组:

SELECT owner, COUNT(*) FROM pet GROUP BY owner;

查询多个表:

SELECT p1.name, p1.sex, p2.name, p2.sex, p1.species FROM pet AS p1, pet AS p2 WHERE p1.species = p2.species AND p1.sex = "f" AND p2.sex = "m";

 

3、修改:

句法:UPDATE tbl_name SET 要更改的列

举例:update pet set sex=f where name=Whistler;

 

4、删除:

句法:DELETE FROM tbl_name WHERE 要删除的记录

练习:

1、Reformat Department Table

select * from (select distinct id from Department order by id) d0 left join (select id,revenue as Jan_Revenue from Department where month = 'Jan') d1 on d0.id = d1.id left join (select id,revenue as Feb_Revenue from Department where month = 'Feb') d2 on d0.id = d2.id ;

2、Delete Duplicate Emails

delete p3 from Person p3,(select p1.Id from Person p1,Person p2 where p1.Id > p2.Id and p1.Email = p2.Email) p4 where p3.Id=p4.Id;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值