MySQL Query - 如何计算连接三个表的第二个表中的外键出现?

时间:2012-10-24 03:15:20

标签: mysql

这是我的数据样本:

product
--------------------------------
| product_id PK | product_name |
--------------------------------
| FRT1          | Apple        |
| FRT2          | Orange       |
| TXT1          | Ribbon       |
--------------------------------

package
-------------------------
| package_id PK | price |
-------------------------
| P001          | 1000  |
| P002          | 1500  |
| P003          | 1000  |
-------------------------

package_detail
---------------------------------
| package_id FK | product_id FK |
---------------------------------
| P001          | FRT1          |
| P002          | FRT1          |
| P002          | FRT2          |
| P003          | FRT2          |
---------------------------------

搜索的关键是product_name,所以如果我搜索“Apple”,结果应该是这样的:

-------------------------------------------
| package_id | price | num_of_package_dtl |
-------------------------------------------
| P001       | 1000  | 1                  |
| P002       | 1500  | 2                  |
-------------------------------------------

我很难加入,任何人都可以帮我查询吗? 提前谢谢〜

2 个答案:

答案 0 :(得分:3)

SELECT  b.package_id, c.price, d.totalCount
FROM    product a
        INNER JOIN package_detail b 
            ON a.product_ID = b.product_ID
        INNER JOIN package c
            ON b.package_ID = c.package_ID
        INNER JOIN 
        (
          SELECT package_id, COUNT(*) totalCount
          FROM package_detail
          GROUP BY  package_id
        ) d ON d.package_ID = b.package_ID
WHERE a.product_name = 'apple'

SQLFiddle Demo

答案 1 :(得分:0)

这样的事情:

选择pd.package_id,p.price,count(*)作为num_of_package_dtl来自package_detail pd join package p on p.package_id = pd.package_id join product pt on pt.product_id = pd.product_id where pd.product_name ='Apple 'group by pd.package_id,p.price