我遇到了一个问题。很难解释,所以我将在下面放置示例:
我的桌子:
region_hotelids
------------------------
EANHotelID | RegionID
------------------------
1234 935
2343 935
1234 850
hotel_attributes
------------------------
EANHotelID | AttributeID
------------------------
1234 1
1234 2
1234 4
1234 6
2343 1
2343 4
2343 2
2343 9
现在我首先需要找到所有具有相同属性的酒店:
SELECT r.EANHotelID, COUNT(c.EANHotelID) AS cat_count
FROM region_hotelid as r
INNER JOIN hotel_attributes AS c ON r.EANHotelID = c.EANHotelID
WHERE c.AttributeID IN (1,2) AND r.RegionID = 935
GROUP BY c.EANHotelID
HAVING cat_count = 2
这可以很好地工作并输出(查找包含这两个属性 ID 的所有 EANHotelID):
result
EANHotelID | cat_count
---------------------------
1234 2
2343 2
现在的问题是,我需要获取这两家酒店共有的所有其他属性 ID。在本例中,这只是 AttributeID 4。我不想要任何不相同的 AttributeIDS(在本例中为 9 和 6)。这是我想添加到原始查询中的内容:
SELECT r.EANHotelID, COUNT(c.EANHotelID) AS cat_count,
(SELECT GROUP_CONCAT(c2.AttributeID) as ids
FROM hotel_attributes as c2
WHERE c2.EANHotelID = r.EANHotelID
AND c.EANHotelID = r.EANHotelID
GROUP BY c2.EANHotelID ORDER BY ids ASC ) as similarIds
FROM region_hotelid as r
INNER JOIN hotel_attributes AS c ON r.EANHotelID = c.EANHotelID
WHERE c.AttributeID IN (9,44) AND r.RegionID = 935
GROUP BY c.EANHotelID
HAVING cat_count = 2
但不是只返回我想要的 id(4 个或全部 - 1,2,4),而是返回与此 EANHotelID 关联的所有 AttributeId:
result
EANHotelID | cat_count | similarIds
----------------------------------------
1234 2 1,2,3,4,6
2343 2 1,2,3,4,9
我完全不知道如何克服这个问题。任何建议或信息将不胜感激!