在一个具有条件的查询中选择3个表


SELECT 3 tables in one query with condition

如何在一个查询中选择3个表并显示所有带价格的产品?

以下是我的数据库结构(MySql):

类别

+-------------+------------+
 category_id  | parent_id  |
+-------------+------------+
  1           |      0     
  2           |      1
  3           |      1
  4           |      1
  5           |      2
  6           |      3

产品分类

+-------------+------------+
 product_id   | category_id|
+-------------+------------+
  54          |      0     
  55          |      2
  56          |      2
  57          |      2
  58          |      3
  59          |      3
  60          |      4

产品

+-------------+------------+
 product_id   |    price   |
+-------------+------------+
  54          |      10.50     
  55          |      11.20
  56          |      1.00
  57          |      22.20
  58          |      32.0
  59          |      32.0
  60          |      22.0

以下是我的情况;

1. table categories : parent_id = '1'  
(result : 2,3,4)
2. table products_to_categories : category_id = result categories(result : 2,3,4) 
(result : 55,56,57,58,59,60)
3. table products : inner join or left join table product to display price where product_id = result products_to_categories(result : 55,56,57,58,59,60)

最终输出

  55 - 11.20
  56 - 1.00
  57 - 22.20
  58 - 32.0
  59 - 32.0
  60 - 22.0

在我发布这个问题之前,这里是我之前的问题(我一直在思考如何继续到条件2)

$sql_all = mysql_query("SELECT cat.parent_id,cat.category_id FROM categories cat WHERE cat.parent_id='1' ");
while($row = mysql_fetch_array($sql_all)) {
echo $row['categories_id'].'<br/>'; 
}

谢谢。

试试这个,

SELECT  c.*
FROM    categories a
        INNER JOIN products_to_categories b
            ON a.category_id = b.category_id
        INNER JOIN products c
            ON b.product_id = c.product_id
WHERE  a.parent_id = 1

这将显示products表中parent_id=1的所有记录。

查看以下查询:

SELECT pro.product_id, SUM(pro.price) 
FROM categories cat 
JOIN products_to_categories ptc USING(category_id)
JOIN products pro ON ptc.product_id = pro.product_id
WHERE cat.parent_id='1'

有了上述解决方案,您可以在未来轻松扩展,以防您想要按特定产品分组。。。

下面的查询应该会得到您想要的结果。

SELECT p.product_id, p.price
FROM products p
JOIN products_to_categories pc ON (pc.product_id = p.product_id)
JOIN categories c ON ((c.category_id = pc.category_id) AND (c.parent_id = "1"))

当然,您可以将parent_id1更改为任何其他值,并相应地获得结果。

注意:我相信在这种情况下,通过在JOIN子句中声明parent_id条件而不是WHERE子句,您将获得更好的性能。