MySQL子查询from和select型子查询的疑惑

各种子查询
http://www.5idev.com/p-mysql_exists_subquery.shtml
https://www.cnblogs.com/zhazhaacmer/p/9858256.html

关于标量子查询的疑惑点:

标量子查询:只查询出一行一列。理解为每行只能查出一列。
select:子查询对每一行都执行,每行只查出一个结果
where:子查询一般只查出一个值(=)

例子:
select子查询

select year, 
    (select amount from table m where month=1 and m.year=table.year) as m1,
    (select amount from table m where month=2 and m.year=table.year) as m2,
    (select amount from table m where month=3 and m.year=table.year) as m3,
    (select amount from table m where month=4 and m.year=table.year) as m4
from table group by year

(代码原文链接:https://blog.csdn.net/paul0127/article/details/82529216)

***注意:***集合函数的列名,如count(),sum(),一般不用select子查询,用连接
栗子:

select s.sid, s.sname, count(cid) as 选课总数, sum(score) as 总成绩
from student as s left join sc
on s.sid = sc.sid
group by s.sid;

(小声哔哔:用select子查询也可以,

select a.Sid, a.Sname, 
(select count(Cid) from SC b where a.Sid = b.Sid group by Sid) as total_course,
(select sum(score) from SC b where a.Sid = b.Sid group by Sid) as total_score
from student a, SC b group by Sid;

但两者有区别,如果有没有选课的学生,则上面的语句显示为0,而下面显示为null.)
连接查询
select子查询

where子查询

SELECT *
FROM employees
WHERE salary =(
    SELECT MIN(salary)
    FROM employees
);

(代码原文链接:https://www.cnblogs.com/zhazhaacmer/p/9858256.html)

行子查询:

SELECT * FROM article WHERE (title,content,uid) = (SELECT title,content,uid FROM blog WHERE bid=2)

以上为个人理解,如有不正确,敬请指出,谢谢~~~~~

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值