【排列组合场景】 =、!=、<>、<=>使用

本文通过创建一个包含四个球队名称的表team,并利用SQL语句生成所有可能的比赛组合,详细解析了如何使用SQL去除重复的比赛配对,同时探讨了!=与<>在判空场景下的区别及正确用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一个叫team的表,里面只有一个字段name,一共有4条记录,分别是a,b,c,d对应四个球队,现在四个球队进行比赛,用一条sql语句显示所有可能的比赛组合

create table team(
 name char(1)
);

insert into team values('a');
insert into team values('b');
insert into team values('c');
insert into team values('d');

select a.name as A,b.name as B from team a,team b order by a.name ; -- 没有去重 aa  bb 类型


select a.name as A,b.name as B from team a,team b where a.name != b.name order by a.name ; -- 没有去重 ab ba 类型  

select a.name as A,b.name as B from team a,team b where a.name <> b.name order by a.name ; -- 没有去重 != 等同于<>的效果

# 利用不等关系去重

select a.name as A,b.name as B from team a,team b where a.name > b.name order by a.name ; -- 去重成功
select a.name as A,b.name as B from team a,team b where a.name < b.name order by a.name ; -- 去重成功



-- != 与 <>的区别

insert into team values (null)

select * from team where name != null; -- 判空无效    
select * from team where name <> null; -- 判空无效
select * from team where name is not null; -- 判空生效


select * from team where name != 'a'; -- 判断左右是否相等,不包含null值
select * from team where name <> 'a'; -- 判断左右是否相等,不包含null值


-- 结论:
--  =  !=  不用来判空,用is null   is not null
-- !=和<>都是不等于的意思,只能说标准不一样,!=在高级语言中表示不等于,<>在ANSI标准中表示不等于
-- 在各种数据库中,基本都支持!= 和 <> ,但也有只支持ANSI标准的数据库软件,所以为了通用还是建议采用<>

-- 如果想筛选出4条记录:b c d null,可以这么写
select * from team where name <> 'a' or name is null;


-- <> 和 <=>的区别
-- <> 是判断两边的字段值是否不等,不等返回true,不包含null
-- <=>是判断两边的字段值是否相等,相等返回true,包含null

select a.name as A,b.name as B from team a,team b where a.name <> b.name order by a.name ;

select a.name as A,b.name as B from team a,team b where a.name <=> b.name order by a.name ;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值