产品搜索3个数据库表

时间:2013-06-11 09:43:04

标签: php html mysql search

我正在尝试在我正在建设的电子商务网站上创建产品搜索功能,但我遇到了一些麻烦。

我有3个表(类别,子类别,产品)

分类表字段:(categoryID,categoryName,active,image)

sub_categories表字段:( categoryID,categoryName,parentCatID,active,image)

产品表字段:(productID,shortDescription,longDescription,image,catID,subCatID,active,price,delivery,weight)

如果用户输入简短描述或长描述的任何部分,或者如果用户键入类别或子类别名称的任何部分,我应该尝试搜索以查找产品,它应该找到这些类别中的所有产品

我不知道是做JOIN还是多个SQL查询。说实话,我已经修了好几个小时,但是他真的已经到了任何地方,现在回到绘图板寻求帮助

我的第一次尝试看起来像这样:

 $catSelect = mysqli_query($con,"SELECT * FROM categories WHERE categoryName LIKE '%{$term}%'"); 
            $row1 = mysqli_fetch_row($catSelect);
 $subCatSelect = mysqli_query($con,"SELECT * FROM sub_categories WHERE categoryName LIKE '%{$term}%' OR parentCatID = '%{$row1[0]}%'");
            $row2 = mysqli_fetch_row($subcatSelect);
            $productSelect = mysqli_query($con,"SELECT * FROM products WHERE short_description LIKE '%{$term}%' OR long_description LIKE '%{$term}%' OR subCatID = '%{$row2[0]}%' OR catID = '%{$row1[0]}%'"); 

我的最后一次尝试看起来像这样

mysqli_query($con,"SELECT * FROM products  INNER JOIN categories ON products.catID = categories.categoryID WHERE categories.categoryName LIKE '%{$term}%'") or die(mysqli_error());

有人可以帮我处理我需要使用的SQL查询吗?

4 个答案:

答案 0 :(得分:3)

试试这个:

SELECT
    p.productID
FROM
    products p
LEFT JOIN categories c
    ON c.categoryID = p.catID
LEFT JOIN sub_categories sc
    ON sc.categoryID = p.subCatID
WHERE
    p.shortDescription LIKE '%keyword%'
    OR p.longDescription LIKE '%keyword%'
    OR c.categoryName LIKE '%keyword%'
    OR sc.categoryName LIKE '%keyword%'

答案 1 :(得分:2)

您需要在所有三个表上使用where子句进行连接,该子句用于查询要搜索的字段。像这样:

select * from 
products
inner join categories on products.catID = categories.categoryID
inner join sub_categories on products.subCatID = sub_categories.categoryID
where
products.shortDescription like '%query%'
or products.longDescription like '%query%'
or categories.categoryName like '%query%'
or sub_categories.categoryName like '%query%'
;

其中query是搜索查询字符串。

答案 2 :(得分:2)

这对你有帮助.....

SELECT * FROM products AS  PT 
LEFT JOIN Categories AS CT ON CT.catID = PT.catID
LEFT JOIN sub_categories  AS SCT ON SCT.subCatID = PT.subCatID
WHERE 
  PT.active = 'YES' AND 
  (PT.shortDescription LIKE '%shortDescription%' OR 
   PT.longDescription LIKE '%longDescription%' OR 
   CT.category LIKE '%category%'  OR 
   SCT.categoryID LIKE '%sub category%' )

你只是使用php varrible你的值,你可以得到你的搜索结果。

答案 3 :(得分:0)

为什么不为此使用lucene-solr?