关于转换left join on 写法的问题

baobao28 2013-03-04 03:27:04
有2个表关联的查询,consult_booking表中illness_condition可能为空,用如下写法可以查询到对应consult_booking表中的所有数据
select *
from consult_booking a
left join code b
on a.illness_condition = b.code
and b.code_type_id = 17;

但如果通过
select *
from consult_booking a, code b
where b.code_type_id = 17
and (a.illness_condition = b.code or a.illness_condition is null);

查询的话,查询结果中consult_booking表中illness_condition不为空的查询到consult_booking表和对应的code表组合起来的字段的完整数据,但如果consult_booking表中illness_condition为空时,查询到的结果为code表中对应类型所有数据consult_booking表和对应的code表所有类型结果的数据,求解决方法
...全文
439 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
  • 打赏
  • 举报
回复
有简单方法不用非要用其他方法
baobao28 2013-03-06
  • 打赏
  • 举报
回复
难道不用union就没有其他的办法了么
UPC子夜 2013-03-05
  • 打赏
  • 举报
回复
首先不知道为什么不让用join 你们领导想考你吗?这种需求,最好的办法就是用join啊 其次 你的sql select * from consult_booking a, code b where b.code_type_id = 17 and (a.illness_condition = b.code or a.illness_condition is null); 有问题,如果a.illness_condition = b.code,这是一个等值连接,没问题 如果a.illness_condition is null,你的sql就变成 select * from consult_booking a, code b where b.code_type_id = 17 and a.illness_condition is null; 这就是a和b两个表的笛卡尔积 当然有问题了 我建议你把这个or改为union sql为: select * from consult_booking a, code b where b.code_type_id = 17 and a.illness_condition = b.code union select a.*, '' as id, '' as code_type_id, '' as value from a where a.illness_condition is null;
baobao28 2013-03-05
  • 打赏
  • 举报
回复
consult_booking表结构如下 id name illness_condition 101 张三 2 100 李四 code表结构如下 id code_type_id code value 128 17 2 有效 129 17 1 无效 希望得到的查询结果如下 id name illness_condition id code_type_id code value 101 张三 2 128 17 2 有效 100 李四 129 17 通过left join on 的方式可以得到希望的查询结果,可是上面要求不让用left join on的方式来写sql,无奈求where条件的方式筛选查询
睿智天成 2013-03-05
  • 打赏
  • 举报
回复
试试下面的效果是不是lz要的 select * from consult_booking a, code b where b.code_type_id = 17 and a.illness_condition and b.code or a.illness_condition is null;
baobao28 2013-03-05
  • 打赏
  • 举报
回复
顶起来,继续问,咋没人回复呢
renwenli07461 2013-03-05
  • 打赏
  • 举报
回复
引用 5 楼 kate_1988 的回复:
SQL code?123456789select * from consult_booking a, code b where b.code_type_id = 17 and a.illness_condition = b.code union select * from consult_booking a, code b where b.code_type_id……
这估计是唯一的办法了,你们领导怎么有简便的不用,非用复杂的呢。。。
kate_1988 2013-03-05
  • 打赏
  • 举报
回复


select *
  from consult_booking a, code b
 where b.code_type_id = 17
   and a.illness_condition = b.code 
union 
select *
  from consult_booking a, code b
 where b.code_type_id = 17
   and a.illness_condition is null

34,590

社区成员

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

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