0

好的,我有两个需要查询的 sql 表,它们是productproduct_to_category

product好像

在此处输入图像描述

product_to_category好像

在此处输入图像描述

我正在尝试查询这两个表,以便我可以选择某个类别号中的所有表,该类别号位于 中product_to_category,但也选择所有状态为 1 的表,这决定了它们是否处于活动状态。我正在尝试在单个查询中执行此操作,到目前为止,我的查询如下所示,问题是我不确定如何将product_id' 匹配在一起以按我的意愿工作。有人可以告诉我如何做到这一点吗?

mysql_query("SELECT * FROM product,product_to_category WHERE product.status = 1 AND product_to_category.category_id = 35 ORDER BY product.sort_order ASC")
4

5 回答 5

3

你应该使用 JOIN

SELECT * FROM product p INNER JOIN product_to_category pc ON p.productid = pc.productid WHERE p.status = 1 AND pc.category_id = 35 ORDER BY p.sort_order ASC

由于您不熟悉连接,我建议阅读以下内容:

SQL 连接的直观解释:

http://www.codinghorror.com/blog/2007/10/a-visual-explanation-of-sql-joins.html

于 2012-05-10T14:31:41.230 回答
3

尝试:

SELECT * FROM product
INNER JOIN product_to_category ON (product.product_id = product_to_category.product_id)
WHERE 
     product_to_category.category_id = 35
     AND
     product.status = 1
于 2012-05-10T14:34:45.540 回答
2

试试这个:

mysql_query("SELECT * FROM product JOIN product_to_category ON (product.product_id = product_to_category.product_id) WHERE product.status = 1 AND product_to_category.category_id = 35 ORDER BY product.sort_order ASC")

于 2012-05-10T14:31:22.607 回答
1

尝试以下查询。更容易理解

SELECT * FROM 
    product a
    JOIN product_to_category b ON a.product_id = b.product_id
WHERE 
    a.stock_status_id = 1
    AND b.category_id = 35;
于 2012-05-10T14:38:37.420 回答
0
mysql_query("SELECT * FROM product p LEFT JOIN product_to_category pc ON (p.id = pc.product_id) WHERE p.status = 1 AND pc.category_id = 35 ORDER BY p.sort_order ASC");

这应该可以解决问题。确保查看 JOINS 及其不同类型

于 2012-05-10T14:32:46.133 回答