php – 在一个带有条件的查询中选择3个表

发布时间:2022-04-30 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了php – 在一个带有条件的查询中选择3个表脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。
何在一个查询中选择3个表并显示所有产品的价格?

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

类别

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

PRoducts_to_categories

+-------------+------------+
 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,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,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

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

脚本宝典总结

以上是脚本宝典为你收集整理的php – 在一个带有条件的查询中选择3个表全部内容,希望文章能够帮你解决php – 在一个带有条件的查询中选择3个表所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。