简体   繁体   English

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

[英]Remove duplicates from sql query for reservation select

I have the following tables: 我有以下表格:

  • rtable 表格
  • reservation 保留

Now rtable has the following columns: 现在, rtable包含以下列:

  • id int primary key id int主键
  • seats int 座位整数
  • position varchar(10) 位置varchar(10)

And reservation has the following columns: reservation包含以下几列:

  • reservation_id int primary key Reservation_id int主键
  • table_id int foreign key(references rtable.id) table_id int外键(引用rtable.id)
  • reservation_date date Reservation_date日期
  • start_hour start_hour

Now I want to perform the following query: use restaurant; 现在,我要执行以下查询: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))))

However this query returns duplicates for rtable.id. 但是,此查询返回rtable.id的重复项。 Is there any way to remove these duplicates 有什么办法可以删除这些重复项

Here is an example output: 这是示例输出: 在此处输入图片说明

If you are using foreign key then why you are not using joins. 如果您使用外键,那么为什么不使用联接。 And why you are checking so much condition, please check this: 以及为什么要检查这么多状况,请检查以下内容:

    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)

Tell me if this solved your issue or give me dataset and condition, I will help you out. 告诉我这是否解决了您的问题,或者告诉我数据集和条件,我将为您提供帮助。

Try this: 尝试这个:

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