我应该将所有数据放在一个 table 中以实现过滤还是使用连接点 table

Should I put all data in one table for Implementing Filtration or use junction table

我考虑过使用联结 table 来避免在我的数据库中重复数据。

所以我有以下架构

公寓:

+----+-------+----------+------------------+        
| ID | Price |  CityID  |  ContractTypeID  |       
+----+-------+----------+------------------+        
|  1 |  200  |    1     |         1        |    
|  2 |  150  |    1     |         2        |
|  3 |  400  |    1     |         2        |  
+----+-------+----------+------------------+ 

便利设施类型:

+----+-------------+        
| ID |     Name    |      
+----+-------------+        
|  1 |  Building   |   
|  2 |  Kitchen    |
|  3 |  Furniture  |  
+----+-------+-----+ 

便利设施:

+----+----------+--------------+    
| ID |  TypeID  |     Name     | 
+----+----------+--------------+
|  1 |     1    |   Security   |
|  2 |     1    |   Parking    |
|  3 |     2    |   Fridge     |
+----+----------+--------------+ 

公寓设施:

+-------------+-----------+    
| ApartmentID | AmenityID |     
+-------------+-----------+
|      1      |     1     |
|      1      |     2     |
|      2      |     1     |
|      2      |     2     |
|      2      |     3     |
+-------------+-----------+ 

我现在的问题是,如何应用一些过滤器,例如我需要 CityID 1 中的所有公寓,价格 < 400,有冰箱和安全。

这也是实现我想要做的事情的最好的 db-design 方法。

预期结果:

AppartmentID: 2, Building Features: Security, Kitchen Features: Fridge

更新:我目前的工作方式

SELECT Price, ID, Amenities.Name as 'Amenity' FROM Apartments
INNER JOIN ApartmentAmenities ON ApartmentAmenities.ApartmentID = Apartments.ID
INNER JOIN Amenities ON ApartmentAmenities.AmenityID = Amenities.ID

WHERE PropertyAmenities.AmenityID IN (1,2) AND Apartments.Price < 300 AND CityID=1

注意:我在此处发布的数据库中使用了不同的数据,但我的重点是方法

您可以对您的便利设施进行筛选,然后对每间公寓进行分组,并检查是否满足所有筛选条件。然后返回您的公寓以获取更多过滤器。像这样的东西。 SQL Fiddle

SELECT AP.ID
FROM Apartments AP
INNER JOIN 
(
    SELECT AA.ApartmentID
    FROM ApartmentAmenities AA
    INNER JOIN Amenities A ON A.ID = AA.AmenityID
    INNER JOIN AmenityTypes AT ON AT.ID = A.TypeID
    WHERE (AT.Name = 'Kitchen' AND A.Name = 'Fridge') OR (AT.Name = 'Building' AND A.Name = 'Security')
    GROUP BY AA.ApartmentID
    HAVING COUNT(DISTINCT A.Name) = 2
)AA 
ON AP.ID = AA.ApartmentID
WHERE CityID = 1 AND  Price < 400

您可以参考这些链接了解更多信息。

https://www.simple-talk.com/sql/learn-sql-server/high-performance-relational-division-in-sql-server/

https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/