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
最后得到结果
总结:
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;


浙公网安备 33010602011771号