mysql基本知识总结
2017-08-15 本文已影响0人
K也许K
此处使用数据库来至于《mysql 必知必会》的数据库
本文章主要对于表单信息查询
- 数据选择
- 基本语法
SELECT DISTINCT * FROM products LIMIT2,5
选取products表中的所有数据,*表示全匹配.mysql不区分大小写,但一般使用大写表示系统语句.limit 2,5是表示只显示第二条后的5条数据,这是数据分页的一种方式,前一个数字表示从第几条数据后开始显示,第二个数字表示显示数据的条数,如果只有一个数字表示从第0条数据后开始显示
SELECT vend_id FROM products
选取products中vend_id列的全部信息
- 基本语法
- 数据筛选使用where
- AND/OR操作符
SELECT vend_id FROM products WHERE vend_id=1001 AND prod_id='ANV01'
选取vend_id为1001,prod_id为ANV01的信息,当AND变为OR时,表示或.
AND
- AND/OR操作符
OR 图片.png
- IN操作符
SELECT vend_id FROM products WHERE vend_id IN (1001,1002,1005)
选取vend_id为1001,1002,1005的数据
- between操作符
SELECT vend_id FROM products WHERE vend_id BETWEEN 1001 AND 1003
选取vend_id在1001与1005之间的数据
- not操作符
SELECT vend_id FROM products WHERE vend_id NOT IN (1001,1002,1005)
选取vend_id不为1001,1002,1005的数据
- like操作符
SELECT prod_name FROM products WHERE prod_name LIKE 'jet%'
选取jet开头的,%是多字符匹配,如果将%改为,时单字符匹配,及jet后加一个字符
%
图片.png
_
- 数据分组
- group by
SELECT cust_id,COUNT(*) AS orders FROM orders GROUP BY cust_id HAVING COUNT(*)>=2
选取数据按照cust_id分组,并且其cust_id所在行的数目大于2.
- group by
group by 所在位置要在where之后,order by之前,having在此处相当于执行了group by后执行的where操作
图片.png- 排列数据
- order by
SELECT prod_id,prod_name,prod_price FROM products ORDER BY prod_id DESC,prod_name
将选取的数据排序.先按照prod_id的信息进行降序排序,DESC表示降序排序,ASC表示升序排序,mysql默认ASC排序,当prod_id相同时,按照prod_name升序排序
- order by
- 子查询
SELECT cust_id FROM orders WHERE order_num IN (SELECT order_num FROM orderitems WHERE prod_id='TNT2')
- 内部联结
- 单表联结
使用INNER JOIN语法
SELECT vend_name,prod_name,prod_price FROM vendors INNER JOIN products ON vendors.vend_id=products.vend_id
使用where语法
SELECT vend_name,prod_name,prod_price FROM vendors , products WHERE vendors.vend_id=products.vend_id
- 单表联结
- 多表联结
SELECT cust_name,cust_contact FROM customers,orders,orderitems WHERE customers.cust_id=orders.cust_id AND orderitems.order_num=orders.order_num
- 自联结
使用子查询
SELECT prod_id ,prod_name FROM products WHERE vend_id = (SELECT vend_id FROM products WHERE prod_id='DTNTR')
使用自联结
SELECT p1.prod_id,p1.prod_name FROM products AS p1,products AS p2 WHERE p1.vend_id=p2.vend_id AND p2.prod_id='DTNTR'
- 外表联结
SELECT customers.cust_id,orders.order_num FROM customers LEFT OUTER JOIN orders ON customers.cust_id=orders.cust_id
SELECT customers.cust_id,orders.order_num FROM customers RIGHT OUTER JOIN orders ON customers.cust_id=orders.cust_id