两个表,关系为1对0或者1对多,查询问题

专注or全面 2013-04-17 10:23:39



create table t_1
(
id int,
remark varchar(20)
)
create table t_2
(
id int,
value1 char(10),
value2 int,
remark varchar(20)
)
--t_1与t_2为 1:0,或者1:1,或者1:n,有对应关系时,关联键为id

-- t_1与t_2的关系中
--当1:0时,A有效
--当1:1时,若t_2中value1 或者value2不为空,则A有效
--当1:N时,在对应的n行t_2中,若存在任何一行value1 或者value2同时为空,则A无效
--求SQL




...全文
185 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
专注or全面 2013-04-17
  • 打赏
  • 举报
回复
引用 5 楼 Vidor 的回复:
不是一样的方法嘛 SQL code?123456select *, case when not exists (select 1 from t_2 where id=t_1.id and value1 is null and value2 is null) then 1 else 0 endfrom t_1
牛逼!!! 这段时间一直都是写单表或者多表直接inner join ,我用什么left join 写的又臭又长,结果还不正确, 没有理由不给分,谢谢!!!
Vidor 2013-04-17
  • 打赏
  • 举报
回复
不是一样的方法嘛
select *,
	case
		when not exists (select 1 from t_2 where id=t_1.id and value1 is null and value2 is null) then 1
		else 0
	end
from t_1
专注or全面 2013-04-17
  • 打赏
  • 举报
回复
引用 3 楼 Vidor 的回复:
一样的逻辑: select * from t_1 where not exists (select 1 from t_2 where id=t_1.id and value1 is null and value2 is null)
你这个查询出来了有效的数据,现在我是想查询t_1中所有的数据,并标明是否有效
Vidor 2013-04-17
  • 打赏
  • 举报
回复
一样的逻辑: select * from t_1 where not exists (select 1 from t_2 where id=t_1.id and value1 is null and value2 is null)
专注or全面 2013-04-17
  • 打赏
  • 举报
回复
简化了说,就是存在对应关系时,对应的t_2中,若value1和value2同时为空时,A无效,否则有效
专注or全面 2013-04-17
  • 打赏
  • 举报
回复
尽量别用union联合两个结果集

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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