mysql求两张表的数据差集
需求如下:
1.查出5⽉1号,还有没有房间可以预定
共两张表:
<_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 '房间床位表';
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
<_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 _code = b.room_code  AND a.bed_code = b.bed_code
WHERE
<_code IS NULL
最后得到结果
总结:
1.使⽤ left join 左关联查询,效果更⾼。
这类的查询需求就是部分差集
sql语句怎么查询两张表的数据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;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。