2021.9.7使用DQL查询数据(一)

USE school;
CREATE TABLE result(
stu_id INT(4),
sub_no INT(4),
exam_date DATE,
score DOUBLE(5,2)
);

学号1-14 科目1-8 成绩30-100 保留两位小数
INSERT INTO result VALUES
(FLOOR(RAND()*14+1),FLOOR(RAND()*8+1),NOW(),
ROUND(RAND()*70+30,2))

IN嵌套查询
SELECT stu_id AS'刘同学学号',score AS '成绩' FROM result WHERE
stu_id IN(SELECT stu_id FROM student WHERE stu_name LIKE '刘%');

关联:
SELECT stu_name,sub_name,score FROM result r
JOIN student s ON r.`stu_id`=s.`stu_id`
JOIN SUBJECT su ON r.`sub_no`=su.`sub_no`
WHERE stu_name LIKE '刘%';
自连接:
SELECT a.stu_id,a.`sub_no`,a.score,b.score FROM result a ,result b
WHERE a.`stu_id`=b.`stu_id` AND a.`sub_no`=b.`sub_no`
AND a.`score`>60 AND b.`score`<60 
自连接JOIN ON 版:
SELECT a.stu_id,a.`sub_no`,a.score,b.score FROM result a 
JOIN result b ON
a.`stu_id`=b.`stu_id` AND a.`sub_no`=b.`sub_no`
WHERE a.`score`>60 AND b.`score`<60 

SELECT a.categoryName AS '父栏目名称', 
b.categoryName AS '子栏目名称' FROM 
category a JOIN category b
ON a.categoryId=b.pid


以谁做主表 不管数据关联与否 主表数据始终存在
SELECT stu_name,score FROM result r
RIGHT JOIN student s ON r.`stu_id`=s.`stu_id`;

SELECT stu_name,score FROM student r
LEFT JOIN result s ON r.`stu_id`=s.`stu_id`;
 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值