第10章 使用MySQL数据库
1.在数据库中插入数据:INSERT语句;
如://插入一整行:
insert into customers values
(NULL,’…’,’…’,’…’), … ;
//插入一行中指定的列内容:
insert into customers (name,city) values
(‘…’,’…’);
//等同于以下形式
insert into cutomers
set name=’…’,
city=’…’;
2.通过输入cmd命令运行sql脚本:
>mysql –u root –p books < G:/Apache/htdocs/ch10/book_insert.sql
或(已进入mysql的情况下)mysql> source G:/Apache/htdocs/ch10/book_insert.sql;
3.1.从数据库中获取数据:
//获取表中的指定列
select name,city
from customers;
//获得表中所有的列和行
select *
from order_items;
//获得表中所有列中符合特定条件的行
select *
from orders
where customerid=3 ;
//可以用简单的操作符、模式匹配语法及AND和OR
select *
from orders
where customerid=3 or customerid=4 ;
3.2.从多个表中获取数据:
①简单双表关联:
select orders.orderid, orders.amount, orders.date
from customers, orders
where customers.name=’…’
and customers.customerid=orders.customerid;
②查找不匹配行:
【左关联:在两个表之间指定的关联条件下匹配数据行,如果右边的表中没有匹配行,结果中就会增加一行,该行右边的列内容为NULL】(对应的右关联同理)
//ON语法
select customers.customerid, customers.name, orders.orderid
from customers left join orders
on customers.customerid=orders.customerid;
//USING语法,不需要指定连接属性所来自的表
select customers.customerid, customers.name
from customers left join orders
using (customerid)
where orders.orderid is null;
③使用表的别名:Aliases (在一个查询的开始创建表的别名,然后在整个查询过程中使用)
select c.name
from customers as c, orders as o, order_items as oi, books as b
where c.customerid=o.customerid
and o.orderid=oi.orderid
and oi.isbn=b.isbn
and b.title like ‘%Java%’;
3.3.以特定顺序获取数据:
如://按照名升序排列
select name, address
from customers
order by name asc; //ORDER BY子句默认为升序(即asc),desc为降序
4.分组、合计数据:
合计函数:avg(列),count(项目),min(列),max(列),std(列),stddev(列),sun(列)
5.LIMIT:
select name
from customers
limit 2, 3; //从customers表中选择name列,返回3行,从第2行开始
6.更新数据库记录:UPDATE语句
如: update customers
set …
where …
order by …
limit …
7.修改表:ALTER TABLE语句
如://改变名称允许的最大长度
alter table customers
modify name char(70) not null;
//删除一列
alter table orders
drop tax;
8.删除数据库中的记录:
①DELETE语句:
如: delete from customers
where customerid=5;
②删除表: 如:drop table tablename;
③删除整个数据库: 如:drop database dbname;
9.cmd退出mysql:
mysql> /q
或 mysql> exit 或 mysql> quit