mysql取两个表差集_mysql 求两张表的数据差集

需求如下:

1.查出5月1号,还有没有房间可以预定

共两张表:

1.room_beds 房间表

create table sys_rooms_beds

(

id int auto_increment

comment '自增IID'

primary key,

room_code int(5) not null

comment '房间号',

bed_code int(5) not null

comment '床位号',

created_at timestamp null

comment '创建时间',

updated_at timestamp null

comment '更新时间'

)

comment '房间床位表';

2.room.bookeds 房间预订表

create table sys_rooms_bookeds

(

id int auto_increment

primary key,

booked_date date not null

comment '预订日期',

room_code int(5) not null

comment '房间号',

bed_code int(5) not null

comment '床位号',

out_trade_no varchar(100) not null

comment '订单号',

created_at timestamp null

comment '创建时间',

updated_at timestamp null

comment '更新时间'

)

comment '房间床位预订表';

可以通过如下sql语句查出5月1号当天可以预订的房间

SELECT

a.room_code,

a.bed_code,

b.*

FROM

`sys_rooms_beds` AS a

LEFT JOIN ( SELECT * FROM sys_rooms_bookeds WHERE booked_date = '2019-05-01' ) AS b ON a.room_code = b.room_code

AND a.bed_code = b.bed_code

WHERE

b.room_code IS NULL

最后得到结果

8a7d5ae0b3efa6fa3fecda1914294764.png

总结:

1.使用 left join 左关联查询,效果更高。

这类的查询需求就是部分差集

SELECT

A.NAME,

A.addr,

A.age

FROM

A

LEFT JOIN ( SELECT * FROM B WHERE NAME = 'kenthy' ) AS C USING ( NAME, addr, age )

WHERE

C.id IS NULL;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值