从sql查询中删除重复项以进行预留选择

时间:2017-06-03 22:21:26

标签: sql

我有以下表格:

  • rtable
  • 预订

现在rtable包含以下列:

  • id int primary key
  • seat int
  • position varchar(10)

reservation包含以下列:

  • reservation_id int primary key
  • table_id int foreign key(引用rtable.id)
  • reservation_date date
  • START_HOUR

现在我想执行以下查询: 使用餐厅;

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的重复项。 有没有办法删除这些重复

以下是输出示例: enter image description here

2 个答案:

答案 0 :(得分:2)

如果您使用外键,那么为什么不使用连接。为什么你要检查这么多条件,请检查一下:

    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)

告诉我,如果这解决了您的问题或给我数据集和条件,我会帮助您。

答案 1 :(得分:1)

试试这个:

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))))