求SQL语句

winnet 2011-11-12 06:19:24
有二个相同结构的表A和表B,结构如下:
p_id varchar(10),p_color varhcar(10),p_size varchar(10)

现在要找出二表中p_id相同,但p_color和p_size不相同的行
最好是速度比较快的,因为二表中数据很多

谢谢!
...全文
49 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
winnet 2011-11-12
  • 打赏
  • 举报
回复
ok谢谢各位的回复,结贴了,这贴表达的意思和实际的意思有点误差,我重开一贴继续。
中国风 2011-11-12
  • 打赏
  • 举报
回复
select * from A,B where a.P_id=b.P_id and( A.p_size<>B.p_size  or A.p_color<>B.p_color)
--小F-- 2011-11-12
  • 打赏
  • 举报
回复
select
*
from
a
where
exists(select 1 from B where p_id=a.p_id)
and
not exists(select 1 from B where p_id=a.p_id and p_color<>a.p_color and p_size<>a.p_size)
-晴天 2011-11-12
  • 打赏
  • 举报
回复
如果单纯连接,在p_id有重复值的时候会出错.
create table a(p_id int,p_color int,p_size int)
create table b(p_id int,p_color int,p_size int)
insert into a select 1,1,1 union all select 1,2,2
insert into b select 1,1,1 union all select 1,2,2
go
select * from A,B where a.P_id=b.P_id and A.p_size<>B.p_size and A.p_color<>B.p_color
-晴天 2011-11-12
  • 打赏
  • 举报
回复
select * from A
where exists(select 1 from B where p_id=a.p_id)
and not exists(select 1 from B where p_id=a.p_id and p_color<>a.p_color and p_size<>a.p_size)
--楼主说的是"和",但我感觉应该这儿或许应该为
-- p_id=a.pid and (p_color<>a.p_color or p_size<>a.p_size)
--即或p_id相同,P_color不同或p_size不同
union all
select * from B
where exists(select 1 from A where p_id=b.p_id)
and not exists(select 1 from A where p_id=b.p_id and p_color<>b.p_color and p_size<>b.p_size)
中国风 2011-11-12
  • 打赏
  • 举报
回复
select * from A,B where a.P_id=b.P_id and A.p_size<>B.p_size and  A.p_color<>B.p_color


select * from A full join B on a.p_id=b.p_id and a.p_size=b.p_size and A.p_color=B.p_color
where nullif(a.P_id,b.P_id) is not null
中国风 2011-11-12
  • 打赏
  • 举报
回复
select * from A full join B on a.p_id=b.p_id and a.p_size=b.p_size where nullif(a.P_id,b.P_id) is not null


对两表互相不存在的数据
pengxuan 2011-11-12
  • 打赏
  • 举报
回复

select A.*,B.* from A inner join B on A.p_id=B.p_id where A.p_color<>B.p_color and A.p_size<>B.p_size

34,575

社区成员

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

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