MySQL常用语句复习

1、分组查询:
(1)  # 查询课程ID为80且实付金额大于1的所有订单的id、实付金额
select id,real_price from t_pay_order_202012 where season_id=80 && real_price > 1
(2)  # 查询所有课程
select distinct season_id from t_pay_order_202012
(3)  # 查询所有课程 及其 最大实付金额、最小实付金额
select season_id,max(real_price),min(real_price) from t_pay_order_202012 group by season_id
(4)  # 查询最小实付金额大于等于xx的所有课程 及其 最大实付金额、最小实付金额
select season_id,max(real_price),min(real_price) from t_pay_order_202012 group by season_id having min(real_price) >= 0
——————————————————————————————————————————————————————–

示例:
test_1表:

test_2表:

2、左连接:
select * from test_1 a left join test_2 b on a.id = b.id      # 详细筛选加“where xxx”

3、右连接:
select * from test_1 a right join test_2 b on a.id = b.id      # 详细筛选加“where xxx”

4、显示内连接:
select * from test_1 a inner join test_2 b on a.id = b.id      # inner可省略,# 详细筛选加“where xxx”
      隐式内连接(自然连接):
select * from test_1 a,test_2 b where a.id = b.id
二者结果一样:

注:
(1)left/right/inner join整合成一张大表,所以后面都可以加“where、group by having、order by、limit”等进行详细筛选
(2)“on a.xx = b.xx”中的字段,应是值唯一的,否则查询结果会是笛卡尔积(也可以注意一下xx字段的数据类型是否一致)

5、全连接:
MySql不支持全连接FUll JOIN,不过可以通过联合UNION来模拟:
left join UNION right join

6、case when then else end
select *,(case when task_id < 60 then ‘不及格’
                when task_id > 60 and task_id < 80 then ‘及格’
                when task_id >= 80 then ‘优秀’
                # when task_id is null then ‘缺席考试’
                else ‘——–刚好及格——–‘
                end) ‘level’
from test_2

7、其他常用的
distinct去重、函数sum()、max()、min()、avg()等,未完待续。。。

本文地址:https://blog.csdn.net/qq_37318583/article/details/110972825

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐