mysql union就像在codeigniter中使用多个表搜索一样查询

时间:2015-08-22 12:03:25

标签: php mysql sql database codeigniter

im trieng对产品进行数据库搜索,有6个表,一切正常,直到我使用product_subcategory表, 它返回相同的1行循环或重复行(大约250行相同的值,可能因为子类包含很多条目)。 product_subcategory包含subcategory_id,category_id,subcategory_name列。产品子类别的信息以这种格式存储在products表中作为subcategory_id(15,24,1,3,8),(所以也许这就是我做错了什么)

我尝试过IN的一些变化,或者..但是现在我卡住了......需要帮助 现在给出一个想法($ branch =' Tokyo'和$ query =' Mobiles')和许多子类别包含单词Mobiles ..

我想要的最终结果是我可以使用

返回结果
    $sql = "SELECT t1.*, t2.*, t3.* , t4.*, t5.*, t6.* 
    FROM 
    products t1, product_details t2, product_warehouses t3, product_courier t4, product_category t5, product_subcategory t6
    WHERE
    t1.product_id = t2.product_id AND
    t1.warehouse_id = t3.warehouse_id AND 
    t4.destination = t3.warehouse_branch AND
    t1.category_id = t5.category_id AND
    t3.warehouse_branch = ".$branch." AND
    t5.category_name LIKE '%".$query."%' UNION
    SELECT t1.*, t2.*, t3.* , t4.*, t5.*, t6.*
    FROM 
    products t1, product_details t2, product_warehouses t3, product_courier t4, product_category t5, product_subcategory t6
    WHERE
    t1.product_id = t2.product_id AND
    t1.warehouse_id = t3.warehouse_id AND 
    t4.destination = t3.warehouse_branch AND
    t1.category_id = t5.category_id AND
    t3.warehouse_branch = ".$branch." AND
    t2.product_name LIKE '%".$query."%' UNION
    SELECT t1.*, t2.*, t3.* , t4.*, t5.*, t6.*
    FROM 
    products t1, product_details t2, product_warehouses t3, product_courier t4, product_category t5, product_subcategory t6
    WHERE
    t1.product_id = t2.product_id AND
    t1.warehouse_id = t3.warehouse_id AND 
    t4.destination = t3.warehouse_branch AND
    t1.category_id = t5.category_id AND
    t3.warehouse_branch = ".$branch." AND
    t1.product_title LIKE '%".$query."%'  UNION
    SELECT t1.*, t2.*, t3.* , t4.*, t5.*, t6.*
    FROM 
    products t1, product_details t2, product_warehouses t3, product_courier t4, product_category t5, product_subcategory t6
    WHERE
    t1.product_id = t2.product_id AND
    t1.warehouse_id = t3.warehouse_id AND 
    t4.destination = t3.warehouse_branch AND
    t1.category_id = t5.category_id AND
    t3.warehouse_branch = ".$branch." AND
    t6.subcategory_id IN (t1.subcategory_id) AND //i think this is where im lost
    t6.subcategory_name LIKE '%".$query."%' 
    ";

当我从所有联合中删除子类别表时,我可以正确执行查询。 希望你们能帮助我。

我使用codeigniter获得最终结果 $ query = $ this-> db-> query($ sql); $ result = $ query-> result_array();

1 个答案:

答案 0 :(得分:0)

查询错误,你为什么6次添加6个相同的表? 试试这个:

$sql = 'SELECT `id`, `name`
FROM 
`products` `p`
JOIN `product_details` `pd` ON `p`.`product_id` = `pd`.`product_id`
JOIN `product_warehouses` `pw` ON `p`.`warehouse_id` = `pw`.`warehouse_id`
JOIN `product_courier` `pco` ON `pco`.`destination` = `pw`.`warehouse_branch`
JOIN `product_category` `pca` ON `pca`.`category_id` = `p`.`category_id`
WHERE
`pw`.`warehouse_branch` = \'' . $branch . '\' AND
`pd`.`product_name` LIKE \'%' . $query . '%\'';