从三个不同的表中获取数据,但它是重复记录

时间:2013-11-26 00:44:44

标签: mysql

我正在尝试从两个不同的表中获取数据,但实际上涉及三个表。

tbl_prosubcategory         procategories             product
ID    Pkey                   ID  Pkey                ID  (P Key)
Cat_id Fkey from category    Categorytype            Cat_id (FKey)
subcatname                                           subcat_id(fkey from prosubcategory) 
                                                     productname
                                                     qty

我从产品表中选择产品密钥并进行以下查询。我只去了一条记录,但它返回了5条重复记录,因为5个记录来自子类别对同一类别。

SELECT c.categoriestype AS categoryname, s.SubCatName AS subcategoryname, p.productname AS productname, p.productprice AS productprice, p.id AS proid, p.productimage AS productimage, p.productthumbnail AS productthumbnail
FROM tbl_ProCategories c, tbl_ProSubCategories s, tbl_products p
WHERE p.subcat_id = s.cat_id
AND p.cat_id = c.id
AND c.id = s.cat_id
LIMIT 0 , 30

1 个答案:

答案 0 :(得分:0)

一个产品属于5个子类别,并且您正在检索subCateName(彼此不同),因此会发生5个结果,我认为从投影中删除SubCatName并使用DISTINCT可以帮助您。

SELECT DISTINCT
  c.categoriestype AS categoryname, 
  p.productname AS productname, p.productprice AS productprice,
  p.id AS proid, p.productimage AS productimage,
  p.productthumbnail AS productthumbnail
FROM tbl_ProCategories c, tbl_ProSubCategories s, tbl_products p
WHERE p.subcat_id = s.cat_id
AND p.cat_id = c.id
AND c.id = s.cat_id
LIMIT 0 , 30