我有三個表產品,屬性和product_properties。表結構和值的子集,給出如下:具有多個條件和多個表的MySQL查詢
products
---------------------------------------------
| id | name | description | price |
---------------------------------------------
| 1 | Camera | Color Camera | 100 |
| 2 | Lens 1 | Camera Lens 1 | 20 |
| 3 | Lens 2 | Camera Lens 2 | 30 |
---------------------------------------------
properties
------------------------------------------
| id | name | display |
------------------------------------------
| 1 | lens_mount | Lens Mount |
| 2 | image_circle | Image Circle |
| 3 | focal_length | Focal Length |
| 4 | lens_family | Lens Family |
------------------------------------------
product_properties
------------------------------------------------
| id | value | product_id | property_id |
------------------------------------------------
| 1 | F-Mount | 2 | 1 |
| 2 | C-Mount | 3 | 1 |
| 3 | 42.01 mm | 2 | 2 |
| 4 | 13.00 mm | 3 | 2 |
| 5 | 10.00 | 2 | 3 |
| 6 | 12.00 | 3 | 3 |
| 7 | Standard | 1 | 4 |
| 8 | Standard | 2 | 4 |
| 9 | Standard | 3 | 4 |
------------------------------------------------
這裏是我的輸出條件:
查找攝像機1(匹配的相機和鏡頭的所有鏡頭由lens_family,這是「標準」在這裏),其具有lens_mount = 'F-摩' 和image_circle> = 40這個毫米和FOCAL_LENGTH> 5
我嘗試以下查詢:
SELECT * FROM products
INNER JOIN product_properties ON products.id = product_properties.product_id
INNER JOIN properties ON properties.id = product_properties.property_id
WHERE (product_properties.value = 'Standard')
AND (properties.name = 'lens_mount' AND product_properties.value = 'F-Mount')
AND (properties.name = 'image_circle' AND product_properties.value >= ABS('40 mm'))
AND (properties.name = 'focal_length' AND product_properties.value >= 5)
但是,如果只有一個條件,則此查詢只會給出正確的結果。在所有條件下它都沒有任何價值。我在OR條件下用OR來代替AND,但也沒有幫助獲得正確的輸出。
任何人都可以整理這個請。提前致謝。
我喜歡這個解決方案。如果有不同的屬性可能具有「Standard」作爲值,那麼您應該先爲'HAVING'子句條件('product_properties.value ='Standard'')添加'properties.name ='lens_family'AND'。 – Tom
@Tom。 。 。非常好的一點。我做了修復。 –
謝謝Gordon&Tom,這個解決方案非常完美! – Lalu