[英]How to select only entries from A which have only values=X in all respective rows in B table?
[英]How can I select all rows in a table a, which have n characteristics given in a table b
我正在制作一個用於出租房屋的網頁。
出版物存儲在這樣的表中
ta_publications
+---+-------------+------+
|id | name | date |
+---+-------------+------+
| 1 | name_001 | ... |
| 2 | name_002 | ... |
| 3 | name_003 | ... |
+---+-------------+------+
我有不同的出版物,它們具有“衛星電視”,“洗衣房清潔”等“功能”。
這些功能將來可能會更改,我希望能夠添加/刪除/修改它們,因此我將它們存儲在表中的數據庫中。
ta_feature_types
+---+-------------+
|id | name |
+---+-------------+
| 1 | Internet |
| 2 | Wi-Fi |
| 3 | satelital tv|
+---+-------------+
與使用表格的出版物相關的
ta_features
+---+-------------+----------------+
|id | type_id | publication_id |
+---+-------------+----------------+
| 1 | 1 | 1 |
| 2 | 2 | 1 |
| 3 | 3 | 1 |
+---+-------------+----------------+
我認為這很容易理解; 有一個名為name_001的出版物,其中有互聯網,無線網絡和衛星電視。
我的問題是:我需要能夠有效地搜索和選擇具有某些功能的所有出版物(房屋)。 例如,所有具有Internet,WiFi和“可帶寵物”功能的出版物。
我只是想出另一個問題:當用戶喜歡一個出版物時,說“ house_003”,我如何獲得它所具有的功能的列表?
如果要按功能名稱獲取出版物:
SELECT p.*
FROM ta_publications p
JOIN ta_features f ON f.publication_id = p.id
JOIN ta_feature_types t ON f.type_id = t.id
WHERE t.name = ? -- feature name
如果您已經知道功能ID :
SELECT p.*
FROM ta_publications p
JOIN ta_features f ON f.publication_id = p.id
WHERE f.type_id = ? -- feature ID
編輯:要獲取與所有多個功能ID匹配的所有出版物:
SELECT p.id, p.name
FROM pub p
JOIN pub_feat pf ON pf.pub_id = p.id
WHERE pf.feat_id IN ? -- list of feature IDs, e.g. (1,2,3)
GROUP BY p.id, p.name HAVING COUNT(*) = ? -- size of list of feature IDs, e.g. 3
要通過發布ID獲取所有功能(我假設為名稱):
SELECT t.name
FROM ta_feature_types t
JOIN ta_features f ON f.type_id = t.id
JOIN ta_publications p ON f.publication_id = p.id
WHERE p.id = ? -- publication ID
有關架構的一些說明:
如上所述,除非發布可以具有相同的功能多次,例如“ 2x Wi-Fi”,否則您不需要ta_features
表中的ID列。
您的表名令人困惑,我可以建議您重命名
ta_features
到ta_publication_features
(或ta_pub_features
)和 ta_feature_types
到ta_features
出於性能原因,您應該在上述JOIN條件中使用的所有列上創建索引(在此處使用原始表名):
ta_publications(id)
ta_features(type_id, publication_id)
ta_feature_types(id)
如果用戶選擇了多個功能,請使用IN
關鍵字和發布的所有功能的列表:
SELECT p.*
FROM ta_publications p
WHERE '1' in (select type_id from ta_features where publication_id = p.id)
AND '2' in (select type_id from ta_features where publication_id = p.id)
AND '3' in (select type_id from ta_features where publication_id = p.id)
您可以使用您選擇的服務器語言通過循環生成以上內容。 即。
SELECT p.*
FROM ta_publications p
WHERE 1=1
//START SERVER LANGUAGE
for (feature in featuresArray){
print("AND '$feature' in (select type_id from ta_features where publication_id = p.id)");
}
//END SERVER LANGUAGE
我認為您想要的是一個子查詢:
select a.*
from ta_publications as a
where '1' in (select type_id from ta_features where publication_id=a.id)
用“ 1”代替您想要的任何其他功能編號。
對於你的第二個問題。 一個簡單的查詢應該做到這一點:
select type_id
from ta_features
where publication_id=[[[id that someone likes]]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.