mysql - 在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 等
我想防止这种情况并拥有其中之一,请帮助我
解决方案
我假设查询的目标是在同一家酒店的每条记录中列出最多 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 床房间。
推荐阅读
- java - 如何用“+”分割字符串,方括号内除外
- c# - 找到玩家右侧/左侧
- c++ - 非常低的 FLOPs/秒,无需任何数据传输
- angular - 如何以角度同时处理多个相同的API调用
- c# - 忽略 HttpClient,C# 中的无效响应标头
- sql-server - 从 Parallels Windows 10 VM 到 MAC Big Sur 上的 Docker Azure SQL Edge 的 Vb.net (Visual Basic) 连接
- python - 为什么 Python 套接字的连接速度比 Java 套接字慢 4.5 倍?
- java - 内存键值缓存是否包含引用值?
- linkedin - Linkedin API 基本个人资料权限
- json - Spark:检索嵌套结构列的数据类型