数据库基础知识:
(1)关联查询
1)横向关联查询:
a、inner join:内关联,只组合数据表中匹配项相等的行。 select * from tbl inner join tb2 on tb1.id=tb2.id
b、left join:左关联,以左面所关联表为基准,左面记录全部显示,右面表中不能匹配上的补null。
c、right join:左关联,以右面所关联表为基准,右面记录全部显示,左面表中不能匹配上的补null
d、full join: 左关联 + 有关联(两个表中的记录相加),不匹配的全部显示
e、cross join: 左关联 * 右关联(两个表中的记录相乘),不需要条件(不要加on)
注:cross join可用在统计数据中,为每行记录添加小计,
如:declare @cnt int
set @cnt=5
select * from tb inner join select @cnt
2)纵向关联查询:
union all:
例如:
declare @tb table(id int primary key identity(1,1),name nvarchar(10),salary decimal(10,2))
insert @tb select 'aa',120.5
union all 'bb',455.12
union all 'cc',500.5
注:添加数据时,去掉all,会去掉添加记录中重复的记录。
3)嵌套子查询:关键字 in exists-----(去掉重复记录)
in(数据集合)
例如:
select * from so where soid in(selet soid from sod where prodid=1) ---查询所有购买了产品1的订单
exists(数据集合)
select * from so a where exists(select soid from sod b where a.soid=b.soid and b.prodid=1)
注:exists 使用过程中,数据集合中查询的表要和外面的表相关联,如sod和so的关联。
4)T-SQL语句:case when ------相当与编程语言中的swith语句
例如:
declare @cnt int
set @cnt=2
case @cnt
when 1 then '结果等于1'
when 2 then '结果等于2'
else '不知道' end
-------另一种书写方式-----
case when @cnt=1 then '结果等于1'
when @cnt=2 then '结果等于2'
else '不知道' end