2017-02-28 61 views
-1

我試圖從postgresSQL中設置下列數據中獲得最佳匹配。Postgres選擇精確匹配ovet集合的行

數據集例如:(以下數據集屬於父母或我要說的是我保持的表稱爲tbl_parent_meta_data動態父屬性)

Filters: Brand=BMW, Wheels=17 & Model=B2017 

根據上面的過濾器,SQL應該返回parentId的唯一匹配濾波器,即:9080 & 9082號文件

+----+----------+-------------+---------------+ 
| Id | AdId  | MetaDataKey | MetaDataValue | 
+----+----------+-------------+---------------+ 
| 1 |  9080 | Brand  | BMW   | 
| 2 |  9080 | Wheels  | 17   | 
| 3 |  9080 | Model  | B2017   | 
| 4 |  9081 | Brand  | BMW   | 
| 5 |  9081 | Wheels  | 18   | 
| 6 |  9081 | Model  | B2016   | 
| 7 |  9082 | Brand  | Audi   | 
| 8 |  9082 | Wheels  | 19   | 
| 9 |  9081 | Model  | A2016   | 
| 10 |  9082 | Brand  | BMW   | 
| 11 |  9082 | Wheels  | 17   | 
| 12 |  9082 | Model  | B2017   | 
+----+----------+-------------+---------------+ 

查詢我用:這工作對我來說,我需要的替代品。

SELECT axd.ad_id adId 
FROM ads_extradata axd 
LEFT JOIN ads a on a.id = axd.ad_id 
LEFT JOIN categories_translations ct ON ct.id = a.category_translation_id 
LEFT JOIN categories_meta_data cmd ON cmd.id = axd.category_metadata_id 
LEFT JOIN languages l ON l.id = ct.language_id 
WHERE cmd.deleted = false AND ct.deleted = false AND a.deleted = false  
AND axd.deleted = false 
AND a.category_translation_id = '" . $categoryTranslation->getId() . "' 
GROUP BY axd.ad_id 
HAVING SUM(
CASE 'Brand' WHEN axd.extra_value::text THEN 10 ELSE 0 END + 
CASE 'Wheels' WHEN axd.extra_value::text THEN 10 ELSE 0 END + 
CASE 'Model' WHEN axd.extra_value::text THEN 10 ELSE 0 END) >= 30 
+0

你嘗試過什麼查詢? –

+0

謝謝Radu,我用我用過的查詢更新了這個問題,結果很好。但是可以替代 – danyal14

回答

1

假設,你可以提取你的過濾器,並應用於查詢

那麼你可以做

SELECT parentid 
FROM table_name 
WHERE (metadatakey, metadatavalue) IN (
     ('Brand', 'BMW'), 
     ('Wheels', '17'), 
     ('Model', 'B2017') 
    ) 
GROUP BY parentid 
HAVING COUNT(DISTINCT metadatakey) = 3; --number of equality filter 
--If you don't have duplicate (metadatakey, metadatavalue) for each 
-- parentid then use COUNT(*) instead 
+1

「where」子句可以簡化爲(('Brand','BMW'),('Wheels','17'),('Model','B2017 '))' –

+0

感謝您的回覆,我會在今天進行測試,然後回覆您。 – danyal14