2

我遇到了一个问题。很难解释,所以我将在下面放置示例:

我的桌子:

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

我完全不知道如何克服这个问题。任何建议或信息将不胜感激!

4

1 回答 1

1

您可以使用另一个INNER JOIN来仅选择所有酒店具有相同属性的行。我将WHERE子句移到JOINsON条件中。

在此处查看一个有效的SQL-Fiddle 示例

请注意,您的HAVING COUNT(..)病情表现不佳。数据库引擎必须在 SELECT 之后检查每个结果集以查看您的HAVING条件是否匹配。我保持不变,但我认为这也应该优化!

SELECT 
  ha.*
FROM
  hotel_attributes ha 
INNER JOIN hotel_attributes ha_other
ON
  ha.AttributeID = ha_other.AttributeID
  AND NOT ha.EANHotelID = ha_other.EANHotelID
  AND ha_other.EANHotelID IN ( SELECT r.EANHotelID
    FROM region_hotelids 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 COUNT(c.EANHotelID) = 2
  )
GROUP BY ha.EANHotelID, ha.AttributeID
于 2013-07-01T18:52:42.940 回答