如何根据案例更改查询

时间:2013-10-05 04:48:00

标签: mysql

我有一个带有以下架构的MySql表。

table_products - "product_id", product_name, product_description, product_image_path, brand_id
table_product_varient - "product_id", "varient_id", product_mrp, product_sellprice, product_imageurl
table_varients - "varient_id", varient_name
table_product_categories - "product_id", "category_id"

用户正在传递category_id,我正在使用

获取该类别的所有项目
my $sql_query = "SELECT
P.product_id, P.product_name,  V.varient_name, PV.product_mrp, PV.product_sellprice, P.product_image_path
FROM
table_products as P
INNER JOIN
table_product_categories as PC 
ON
  P.product_id = PC.product_id
INNER JOIN
table_product_varients as PV
ON
P.product_id = PV.product_id
INNER JOIN
table_varients as V
ON
V.varient_id = PV.varient_id
where 
PC.category_id = '$cate_id' ";

我想修改此查询,以便,如果product_imageurl在table_product_varients中可用,则获取该图像,否则从table_products获取product_image_path图像。目前查询是从table_products中获取product_image_path图像。

请有人帮助我。

任何帮助都将受到高度赞赏。

2 个答案:

答案 0 :(得分:2)

你可以避免CASE:

SELECT
    P.product_id, 
    P.product_name, 
    V.varient_name, 
    PV.product_mrp, 
    PV.product_sellprice, 
    IFNULL(PV.product_imageurl, P.product_image_path) AS product_imageurl
FROM
    table_product_categories PC,
    table_varients V, 
    table_products P
        LEFT JOIN table_product_varients PV ON P.product_id = PV.product_id
where 
    P.product_id = PC.product_id
    AND V.varient_id = PV.varient_id
    AND PC.category_id = '$cate_id'

答案 1 :(得分:1)

替换此

P.product_image_path

CASE 
  WHEN PV.product_imageurl IS NULL OR PV.product_imageurl = '' then
       P.product_image_path
ELSE 
     PV.product_imageurl
END