使用3个表进行SQL查询时面临问题

使用3个表进行SQL查询时面临问题,sql,Sql,我在形成sql查询时遇到了一个问题 我有三张桌子 表1-产品 |---------------------|------------------|------------------| | ProductId | ProductName | BrandId | |---------------------|------------------|------------------| | P1 | Abc

我在形成sql查询时遇到了一个问题

我有三张桌子

表1-产品

|---------------------|------------------|------------------|
|      ProductId      |   ProductName    |      BrandId     |
|---------------------|------------------|------------------|
|          P1         |       Abcd       |         B1       |
|---------------------|------------------|------------------|
|          P2         |       xyz        |         B2       |
|---------------------|------------------|------------------|

表2-数据包

|---------------------|------------------|
|      ProductId      |    PacketName    |
|---------------------|------------------|
|          P1         |       Pac1       |
|---------------------|------------------|
|          P1         |       Pac2       |
|---------------------|------------------|
|          P2         |       Pac3       |
|---------------------|------------------|
表3-品牌

|---------------------|------------------|
|        BrandId      |     BrandName    |
|---------------------|------------------|
|          B1         |     Brand1       |
|---------------------|------------------|
|          B2         |     Brand2       |
|---------------------|------------------|
我期望的输出如下

|---------------------|------------------|------------------|------------------|
|      ProductId      |   ProductName    |     BrandName    |       Packets    |
|---------------------|------------------|------------------|------------------|
|          P1         |       Abcd       |     Brand1       |          2       |
|---------------------|------------------|------------------|------------------|
|          P2         |        xyz       |     Brand2       |          1       |
|---------------------|------------------|------------------|------------------|
我面临的问题是查询形成。我们将不胜感激。提前谢谢

您可以执行以下操作:

select
  p.productid,
  p.productname,
  b.brandname,
  count(*) as packets
from product p
join brand b on b.brandid = p.brandid
left join packet k on k.productid = p.productid
group by p.productid, p.productname, b.brandname

提示:
加入
<代码>分组依据。您尝试了什么?找出您正在使用的RDBMS。然后看看@GordonLinoff,我尝试了join和groupby,但不知何故得到了不同的结果。