sql中级语句

创建联结
select n_title,n_content,t_name,t_memo from nrc_news,nrc_type where nrc_news.t_id=nrc_type.t_id;
select n_title,n_content,t_name,t_memo from nrc_news,nrc_type ;
笛卡尔积:
由没有联结条件的表关系返回的结果为笛卡尔积。检索出的行的数目将是第一个表中的行数乘以第二个表中的行数。

提示:返回笛卡尔积的联结也叫叉联结。

内联结:
select n_title,n_content,t_name,t_memo from nrc_news inner join nrc_type on nrc_news.t_id=nrc_type.t_id;
上述语句用法与第一条一样。

多表联结:
select r_content,n_title,n_content,t_name,t_memo from nrc_review,nrc_news,nrc_type where nrc_review.n_id=nrc_news.n_id and nrc_news.t_id=nrc_type.t_id;

select r_content,n_title,n_content,t_name,t_memo from nrc_review,nrc_news,nrc_type where nrc_review.n_id=nrc_news.n_id and nrc_news.t_id=nrc_type.t_id and t_memo='小火龙';

创建高级联结:
别名:
select r_content,n_title,n_content,t_name,t_memo from nrc_review as r,nrc_news as n,nrc_type as t where r.n_id=n.n_id and n.t_id=t.t_id;

自联结:
select n_id,n_title,n_content,t_id from nrc_news where t_id=(select t_id from nrc_news where n_title='梦幻');

外联结:
select nrc_news.n_title,nrc_news.n_content,nrc_type.t_name,nrc_type.t_memo from nrc_news left outer join nrc_type on nrc_news.t_id=nrc_type.t_id;
select nrc_news.n_title,nrc_news.n_content,nrc_type.t_name,nrc_type.t_memo from nrc_news right outer join nrc_type on nrc_news.t_id=nrc_type.t_id;

提示:
外联结的类型:
外联结两种类型:左外联结和右外联结,它们唯一的区别是所关联的表的顺序。换句话说,调整FROM或WHERE子句中表的顺序,左外联结可以转换为右外联结。
还存在另一种外联结,就是全外联结,它检索两个表中的所有行并关联那些可以关联的行。与左右外联结包含一个表的不关联的行不同,全外联结包含两个表的不关联的行。

带有聚集函数的联结
select t.t_id,COUNT(n.t_id)as tchoose from nrc_type as t Inner join nrc_news as n on t.t_id=n.t_id group by t.t_id;

组合查询:

select * from nrc_type where t_id in(1,2,3)
union
select * from nrc_type where t_name ='公告';
union相当于或
上述语句等于
select * from nrc_type where t_id in(1,2,3) or t_name ='公告';

原文地址:https://www.cnblogs.com/daochong/p/4870007.html