从一个查询中的多个表中提取数据并将数据匹配在一起

时间:2012-05-10 14:27:56

标签: php sql

好的我有两个我需要查询的sql表productproduct_to_category

product看起来像

enter image description here

product_to_category看起来像

enter image description here

我正在尝试查询这两个表,以便我可以选择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")

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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")

答案 3 :(得分: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;

答案 4 :(得分: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及其不同类型