2014-01-29 85 views
1

在該表中:選擇一個值,如果它存在,另一個如果不是

|value_id|entity_type_id|attribute_id|store_id|entity_id|value 
|9289729 |4    |62   |0  |765985 |default value 
|9289730 |4    |62   |1  |765985 |value in spanish 
|9289731 |4    |62   |2  |765985 |value in dutch 

我需要得到用於STORE_ID的值(即可以是1,2或3)或默認值(STORE_ID = 0)如果它不存在。
它必須包括幾個INNER組成一個更大的查詢連接,它看起來像這樣至今:

SELECT DISTINCT `p2c`.`product_id`, `name_id`.`value` AS `name`, `short_description_id`.`value` AS `short_description` FROM `catalog_category_product` AS `p2c` 
INNER JOIN `catalog_product_entity_int` AS `status` ON p2c.product_id = status.entity_id AND status.value = 1 
INNER JOIN `catalog_product_entity_int` AS `visibility` ON p2c.product_id = visibility.entity_id AND visibility.value = 4 
INNER JOIN `catalog_product_entity_varchar` AS `name_id` ON p2c.product_id = name_id.entity_id AND name_id.attribute_id = 60 
INNER JOIN `catalog_product_entity_text` AS `short_description_id` ON p2c.product_id = short_description_id.entity_id AND short_description_id.attribute_id = 62 
WHERE (category_id IN ('1224')) 

所以,我想是這樣的:

SELECT DISTINCT `p2c`.`product_id`, `name_id`.`value` AS `name`, `short_description_id`.`value` AS `short_description` FROM `catalog_category_product` AS `p2c` 
INNER JOIN `catalog_product_entity_int` AS `status` ON p2c.product_id = status.entity_id AND status.value = 1 
INNER JOIN `catalog_product_entity_int` AS `visibility` ON p2c.product_id = visibility.entity_id AND visibility.value = 4 
INNER JOIN `catalog_product_entity_varchar` AS `name_id` ON p2c.product_id = name_id.entity_id AND name_id.attribute_id = 60 
INNER JOIN `catalog_product_entity_text` AS `short_description_id` ON p2c.product_id = short_description_id.entity_id 
AND short_description_id.attribute_id = 62 
//start of not real mysql code 
AND ((short_description_id.store_id = 3) IF THERE IS A VALUE FOR THIS STORE_ID 
     OR (short_description_id.store_id = 0) OTHERWISE) 
//end of not real mysql code 
WHERE (category_id IN ('1224')) 

哦,如果有問題,我使用Zend的mysql。
任何想法?

+0

[Coalese()](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators的.html#function_coalesce)? –

回答

1

一種方法是左連接兩次到catalog_product_entity_text。一旦ID 0,而另一個用於ID 3,然後執行COALESCE在你選擇

SELECT 
.. 
COALESCE(`short_description_id`.`value` , `short_description_id_DEFAULT`.`value`) AS `short_description` 
.. 
FROM 
... 

    LEFT JOIN `catalog_product_entity_text` AS `short_description_id` 
    ON p2c.product_id = short_description_id.entity_id 
     AND short_description_id.attribute_id = 62 
     AND (short_description_id.store_id = 3) 

    LEFT JOIN `catalog_product_entity_text` AS `short_description_id_DEFAULT` 
    ON p2c.product_id = short_description_id.entity_id 
     AND short_description_id.attribute_id = 62 
     AND (short_description_id.store_id = 0) 
+0

謝謝你的回答康拉德,我今天早上有幾張照片照顧好,然後我會試試你的解決方案,我會盡快回復你 – OSdave

相關問題