连接查询的一点问题

yumanqing 2007-08-06 05:25:01
表A
code name
001 aaa
002 bbb
003 ccc
004 ddd
表B
code qty
001 200
004 500

现在想得到的查询结果是如果是表A的全部数据,如果是表B有的从表B提取数据,没有从表A提取
即:
code name qty
001 aaa 200
002 bbb
003 ccc
004 dddd 500
...全文
108 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
ojuju10 2007-08-07
  • 打赏
  • 举报
回复
用left join

select a.code,a.name,b.qty from a left join b
on a.code=b.code
order by a.code
yumanqing 2007-08-07
  • 打赏
  • 举报
回复
paoluo(一天到晚游泳的鱼)
感谢,多一个WHERE
waitxing 2007-08-06
  • 打赏
  • 举报
回复
--建立测试数据
declare @a table(code varchar(10),name varchar(10))
insert into @a select '001','aaa'
insert into @a select '002','bbb'
insert into @a select '003','ccc'
insert into @a select '004','ddd'
declare @b table(code varchar(10),qty int)
insert into @b select '001',200
insert into @b select '004',500
--执行查询
select A.*,B.qty from @a A left join @b B on A.code=B.code
--结果
code name qty
--- ---- ----
001 aaa 200
002 bbb NULL
003 ccc NULL
004 ddd 500
paoluo 2007-08-06
  • 打赏
  • 举报
回复
try

select cup.ZNO,cu.cCode,cu.cName,cu.cClass,cup.iYear,cup.PlanMoney
from cu_customerBasic cu
left join cu_customerYearplan cup
on cu.cCode=cup.cCode and cup.iYear=2007
Where
cu.DistrictCode like '05%' AND
cu.OperationCode like '01%'
yumanqing 2007-08-06
  • 打赏
  • 举报
回复
其实我的原查查询语句是这样的
select cup.ZNO,cu.cCode,cu.cName,cu.cClass,cup.iYear,cup.PlanMoney
from cu_customerBasic cu
left join cu_customerYearplan cup
on cu.cCode=cup.cCode and cup.iYear=2007 and
cu.DistrictCode like '05%' AND
cu.OperationCode like '01%'

即还要从cu_customerBasic表中筛选符合条件的,可是每次都是全部的?怎么回事
paoluo 2007-08-06
  • 打赏
  • 举报
回复
Select
A.code,
A.name,
B.qty
From
A
Left Join
B
On A.code = B.code
paoluo 2007-08-06
  • 打赏
  • 举报
回复
LEFT JOIN

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧