PHP 和 Mysql 学习笔记(三)

1. mysql 定界符(反引号`)

当标示符是一个受限的词或包含特殊的字符时使用
select * from `select` where `select`.id >100;
create table orders(`my orders` varchar(100)...);

2. 数据库的大小写

linux下的数据库和表名的大小写是敏感的
其他的数据库对象不区分大小写

3. mysql 分组语句和嵌套子查询

员工表 emp( empno, name, tel, deptno, sal )
部门表 dept( deptno, dname, addr )

显示每个部门收入最高的职工信息
select * from emp
where sal in (
select max(sal)
from emp
group by deptno
);

4. mysql 查询排序 ( SQL Order By )

SELECT "栏位名"
FROM "表格名"
[WHERE "条件"]
ORDER BY "栏位名" [ASC, DESC]

ASC 代表结果会以由小往大的顺序列出,而 DESC 代表结果会以由大往小的顺序列出,默认值为 ASC。

我们可以照好几个不同的栏位来排顺序。在这个情况下, ORDER BY 子句的语法如下(假设有两个栏位):
ORDER BY "栏位一" [ASC, DESC], "栏位二" [ASC, DESC]
若我们对这两个栏位都选择由小往大的话,那这个子句就会造成结果是依据 "栏位一" 由小往大排。若有好几笔资料 "栏位一" 的值相等,那这几笔资料就依据 "栏位二" 由小往大排。

5. mysql limit 子句

数据表同3,查询薪水最低的5名员工。
select * from emp order by sal limit 0, 5;
返回值从第一行开始(第一行偏移量为0)可简写为:
select * from emp order by sal limit 5;
查询3-7号员工信息:
select * from emp limit 2, 5;
这里的 limit 子句是 mysql 特有的,是大多数其他的关系型数据库所没有的。

6. mysql 数据表关联

双表关联
数据表同3,查询某个部门的职工号,姓名:
select emp.empno, emp.name dept.dname
from emp, dept
where dept.name = '软件部'
and emp.deptno = dept.deptno;

多表关联
举例在线书店数据库
客户表 customers (customerid, name, address, city)
定单表 orders (orderid, customerid, amount, date)
书籍表 books (isbn, author, title, price)
订单与图书关联的表 book_items (orderid, isbn, quantity)
查询至少定购了一本关于 java 的书籍的顾客:
select customers.name
from customers, orders, order_items, books
where customers.customerid = order.customerid
and orders.orderid = order_items.orderid
and order_items.isbn = books.isbn
and books.title like '%java%';

在这里同样可以使用表的别名(alias),以上可改写为:
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%';

查找不匹配行,这里查找没有订购任何商品的顾客:
select customers.customerid, customers.name
from customers left join orders
using (customerid)
where orders.orderid is null

这里使用了一个左关联将 customers 表和 orders 表关联起来,如果右边的表中没有匹配行就在结果中加一行,该行右边的列为 null,在这里关联条件所使用的语法一种是上面的 using,它并不需要指定连接属性所来自的表,所以要使用 using 子句,两个表中的列必须有同样的名称,另外还有一个关联条件的语法是 on,它需要指定连接属性所来自的表:
....
on customers.customerid = orders.customerid
....

A left join(左连接)包含所有的左边表中的记录甚至是右边表中没有和它匹配的记录。
同理,也存在着相同道理的 right join(右连接),即包含所有的右边表中的记录甚至是左边表中没有和它匹配的记录。
而full join(全连接)顾名思义,左右表中所有记录都会选出来。

Tags: mysql, SQL, 笔记

相关日志

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

还没有评论。

发表评论

(必填)

(必填)


*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Comment moderation is enabled. Your comment may take some time to appear.