繁体   English   中英

从SQL查询中删除重复项以进行保留选择

[英]Remove duplicates from sql query for reservation select

我有以下表格:

  • 表格
  • 保留

现在, rtable包含以下列:

  • id int主键
  • 座位整数
  • 位置varchar(10)

reservation包含以下几列:

  • Reservation_id int主键
  • table_id int外键(引用rtable.id)
  • Reservation_date日期
  • start_hour

现在,我要执行以下查询:use restaurant;

select id,position,seats from rtable,reservation 
            where (seats >= 6 and position = 'Indoors') 
            and (not exists(select * from reservation where table_id = id) or(
            (exists(select 1 from reservation where table_id = id) and
                (reservation_date != '2017-05-23' or reservation.start_hour != 16))))

但是,此查询返回rtable.id的重复项。 有什么办法可以删除这些重复项

这是示例输出: 在此处输入图片说明

如果您使用外键,那么为什么不使用联接。 以及为什么要检查这么多状况,请检查以下内容:

    SELECT rt.id, rt.position, rt.seats FROM rtable rt LEFT JOIN reservation res
    ON rt.id = res.table_id AND rt.seats >=6 AND rt.position = 'Indoors' AND
    (res.reservation_date != '2017-05-23' AND res.start_hour != 16)

告诉我这是否解决了您的问题,或者告诉我数据集和条件,我将为您提供帮助。

尝试这个:

select distinct id,position,seats from rtable,reservation 
            where (seats >= 6 and position = 'Indoors') 
            and (not exists(select * from reservation where table_id = id) or(
            (exists(select 1 from reservation where table_id = id) and
                (reservation_date != '2017-05-23' or reservation.start_hour != 16))))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM