MySQL_Task_2
1.基础语句
-
select(选数据)
-
select <列名>#选择列 from<表名>#从哪个表
-
where(筛选符合条件的数据)
-
select <列名>#选择列 from<表名>#从哪个表 where<条件表达式>#筛选条件
-
星号(*)可以代表全部列
-
select *#选择所有列 from<表名>#从哪个表
-
-
distinct(删除重复行)
-
select distinct <列名>#删除列中重复的数据 from<表名>#从哪个表
2.运算符(算数&比较&逻辑&位运算)
(类比c语言)
-
运算符
-
加 (+)
-
减 (-)
-
乘 (*)
-
除(/)
-
取余 (%)
-
-
比较运算符
-
相等 (=)
-
不相等 (<>、!=)
-
大于 (>)
-
大于等于 (>=)
-
小于 (<)
-
小于等于 (<=)
-
在两值之间 (between )
-
不在两值之间 (not between)
-
in (在集合中)
-
not in (不在集合中)
-
<=> (比较两个null的值是否相等)
-
like (模糊匹配)
-
rlike (正则匹配)
-
is null (为空)
-
is not null (不为空)
-
-
逻辑运算符
-
not(逻辑非)
-
and(逻辑与)
-
or(逻辑或)
-
xor(逻辑异或)
-
-
位运算符
-
&(按位与)
-
|(按位或)
-
^(按位异或)
-
!(取非)
-
<<(左移)
-
>>(右移)
-
3.练习1
1.
-
select product_name,sale_price,purchase_price from product where sale_price - purchase_price >= 500
-
select product_name,sale_price,purchase_price from product where sale_price - purchase_price >= 500 or purchase_price - sale_price <= 500
2.
-
select product_name,product_type,profit from product where sale_price * 0.9 - purchase_price > 100
4.对表进行聚合查询
常用函数
-
count:计算表中行数
-
sum:计算表中数值中数据的和
-
avg:计算表中数值平均值
-
max:求出表中任意列中数据的最大值
-
min:求出表中任意列中数据的最小值
5.对表进行分组
#group by select <列名1>,<列名2>,<列名3>,... from <表名> group by <列名1>,<列名2>,<列名3>,...
#加上where语句 select product_name,count(*) from product where sale_price < 5000 group by product_name
#加上having语句 #having的对象必须是select 有的列名 select product_type,sum(sale_price) from product group by product_type having sum(sale_price) < 5000
6.排序
-
select <列名1>,<列名2>,<列名3>,... from <表名> order by <排序基准列1>,<排序基准列2>,...
-
-- 降序排列 select product_id, product_name, sale_price, purchase_price from product order by sale_price DESC; -- 多个排序键 select product_id, product_name, sale_price, purchase_price from product order by sale_price, product_id; -- 当用于排序的列名中含有NULL时,NULL会在开头或末尾进行汇总。 select product_id, product_name, sale_price, purchase_price from product order by purchase_price;
7.练习2
题5:
请指出下述SELECT语句中所有的语法错误。
SELECT product_id, SUM(product_name)/*错误:product_name 不是可以进行sum运算的类型*/ #本SELECT语句中存在错误。 FROM product GROUP BY product_type WHERE regist_date > '2009-09-01';
题6:
请编写一条SELECT语句,求出销售单价(sale_price列)合计值大于进货单价(purchase_price列)合计值1.5倍的商品种类。
select product_type ,sum(sale_price),sum(purchase_price) from product group by product_type having sum(sale_price) > 1.5 * sum(purchase_price)
题7:
此前我们曾经使用SELECT语句选取出了product(商品)表中的全部记录。当时我们使用了ORDERBY子句来指定排列顺序,但现在已经无法记起当时如何指定的了。请根据下列执行结果,思考ORDERBY子句的内容。
select * from product order by regist_date