首页 > 解决方案 > 在mysql中使用自连接时防止重复结果

问题描述

我有一些酒店,每个房间都有不同的酒店视图,而我的最终用户想要 3 个房间,例如每个房间是 2 张床,我必须为此组合记录,有时某些字段可能会重复,这并不重要,并且在这种情况下,用户可能有不同的房间类型我以每个房间有 2 个床号为例:我在得到结果时遇到问题:我在“mysql”中使用自加入,一切都是真的,但有些问题是有相同的行这种情况这是我的代码:

    SELECT
   table1.id,
   table2.id,
   table3.id,
   table1.num_bed,
   table2.num_bed,
   table3.num_bed 
   LEFT JOIN
      tour_package table2 
      ON table1.tour_id = table2.tour_id 
      AND table1.hotel_id = table2.hotel_id 
      AND table1.start_date = table2.start_date 
   LEFT JOIN
      tour_package table3 
      ON table2.tour_id = table3.tour_id 
      AND table2.hotel_id = table3.hotel_id 
      AND table2.start_date = table3.start_date 
WHERE
   table1.num_bed = 2 
   AND table2.num_bed = 2 
   AND table3.num_bed = 2

结果是:

在此处输入图像描述

请注意id,一个是table1.id,二是table2.id,三是table3.id

结果我们有一些结果,例如:1-2-1 1-1-2 等
我想防止这种情况并拥有其中之一,请帮助我

标签: mysqlsqlrelational-database

解决方案


我假设查询的目标是在同一家酒店的每条记录中列出最多 3 个房间,用于相同的旅行和日期,有 2 张床。

(老实说,我不明白查询的重点,因为它会在 tour_package 表中列出所有 2 床房间。)

这意味着不仅1-1-2和1-2-1是重复的,而且2nd 1也是冗余信息。在酒店号。7 只有 2 个房间满足此条件:1 和 2。

在连接条件中,我要求从每个表中返回具有不同 id 的记录。这将强制查询返回记录中唯一 ID 的列表。

SELECT
   table1.id,
   table2.id,
   table3.id,
   table1.num_bed,
   table2.num_bed,
   table3.num_bed 
FROM tour_package table1
LEFT JOIN
      tour_package table2 
      ON table1.tour_id = table2.tour_id 
      AND table1.hotel_id = table2.hotel_id 
      AND table1.start_date = table2.start_date
      AND table1.id<table2.id 
LEFT JOIN
      tour_package table3 
      ON table2.tour_id = table3.tour_id 
      AND table2.hotel_id = table3.hotel_id 
      AND table2.start_date = table3.start_date
      AND table2.id<table3.id 
WHERE
   table1.num_bed = 2 
   AND table2.num_bed = 2 
   AND table3.num_bed = 2

但是,如果酒店中至少有 2 个符合上述条件的房间,则上述查询仍可能返回冗余数据。假设 2 个房间的 id 为 1 和 2,查询将返回 1, 2, null 和 2, null, null。为了克服这个问题,我只想写:

select id, hotel_id from tour_package
where tour_package.num_bed=2
order by tour_id, hotel_id, start_date

原因:即使您的查询将在您的 tour_package 表中显示所有 2 床房间。


推荐阅读