SQL 筑基 初阶1
其他
2019-01-17 11:01:16
阅读次数: 0
1 返回每个产品相关的账号数量
Select product_id,count(*) as accounts_per_product
from Contacts
Group by product_id;
注 :
这里引出了一个小问题:
SELECT Count(*) As MyCount FROM name 这个语句是什么意思?
答:Count()是一个聚合函数,name是表名。这条语句是统计name这个表有多少条数据,并将查出的总数的结果列名设为MyCount。
小知识:
select * 查询出的是所有的记录
select count(*)查询出的是记录的条数
count行数....有几行,就得到几
相反, 获取每个账号相关的产品信息:
SELECT account_id,Count(*)as products_per_account
FROM Contscts
GROUP BY account_id;
更复杂的,比如找到相关账号最多的产品:
Select c.product_id,c.account_per_product
From(
select product_id,Count(*)as accounts_per_product
from Contacts
group by product_id
) AS c
Having c.accounts_per_product=Max(c.accounts_per_product)
注:关于字段作为其中某一步的查询结果
2 子查询补充:
oracle: 子查询(子查询自身只能返回一个单独的值):
1子查询放在select后面,作为其中的一个字段返回。
select u.username,(select d.departname from t_depart d where d.departid = u.departid) from t_user u;
2子查询放在from后面,作为一张临时表。
select * from (select username,sex s from t_user where departid=1) where s = '男';
3 子查询放在where后面,作为条件的一部分。
select * from t_user where departid = (select departid from t_depart where departname = '财务部');
3 接上面,更新或删除
insert into Contacts(product_id,account_id)Values(456,34);
delete from Contacts where product_id =456 and account_id=34
使用交叉表的好处:
在许多数据库中,声明某一列为外键会隐式地为该列创建索引,这可比用逗号做分隔符高效的多了。
转载自blog.csdn.net/Kurapika47/article/details/83821830