查询操作数据库

时间:2013-11-23 09:24:35

标签: php mysql sql database resultset

我正在使用一些过滤器来显示产品。滤色器,如颜色,价格和东西。

链接:http://www.applechain.com/products/iPod.php

我使用此查询

$sql = "Select * 
  from tbl_product  
  where device='iPhone'  
    and (color='$c1'   
      or color='$c2'    
      or color='$c3'    
      or color='$c4'    
      or color='$c5'    
      or color='$c6'    
      or color='$c7'    
      or color='$c8'    
      or color='$c9'    
      or color='$c10'   
    ) and (storage='$cp1'    
      or storage='$cp2'    
      or storage='$cp3'    
      or storage='$cp4'    
      or storage='$cp5'   
    ) and (f_unlock='$factory')    
    and (warranty='$warranty')    
    and (price >= '$price1'    
      and price <= '$price2'   
    ) 
  order by product_id desc";

现在问题是我想显示结果,即使所有查询都不满意。如果只有几个选项匹配,我想在此基础上显示结果。

我会感激帮助。

2 个答案:

答案 0 :(得分:1)

$sql = "SELECT *       
        FROM tbl_product
        WHERE device = 'iPhone'
        AND color IN ('$c1', '$c2', '$c3', '$c4', '$c5', 
            '$c6', '$c7', '$c8', '$c9', '$c10') 
        AND storage IN ('$cp1', '$cp2', '$cp3', '$cp4', '$cp5') 
        AND f_unlock = '$factory'
        AND warranty = '$warranty'
        AND ((price >= '$price1') AND (price <= '$price2')) 
        order by product_id desc";

答案 1 :(得分:0)

尝试类似这样的查询:

$sql = "
    SELECT 
        *, 
        1 as order_prority 
    FROM tbl_product
    WHERE 
        device = 'iPhone'
        AND color IN ('$c1', '$c2', '$c3', '$c4', '$c5', 
            '$c6', '$c7', '$c8', '$c9', '$c10') 
        AND storage IN ('$cp1', '$cp2', '$cp3', '$cp4', '$cp5') 
        AND f_unlock = '$factory'
        AND warranty = '$warranty'
        AND (price BETWEEN '$price1' AND '$price2') 
    UNION SELECT 
        *, 
        2
    FROM tbl_product
    WHERE 
        device = 'iPhone'
        AND (
            color IN ('$c1', '$c2', '$c3', '$c4', '$c5', 
                      '$c6', '$c7', '$c8', '$c9', '$c10') 
            OR storage IN ('$cp1', '$cp2', '$cp3', '$cp4', '$cp5') 
            OR f_unlock = '$factory'
            OR warranty = '$warranty'
            OR (price BETWEEN '$price1' AND '$price2') 
        )
    ORDER BY order_prority ASC, product_id DESC
";

在所有情况下,您都会收到一些结果。如果第一个SELECT(更严格)返回某些内容,则数据将在顶部包含这些结果,第二个SELECT(更软)将在最后。如果第一个SELECT将不返回任何内容,则您将获得来自第二个软查询的数据。