检索三个表之间一对多关系中的一行
我有以下三个表:
----Product----
PRODUCT_ID DESC
1 'Pencil'
2 'Paper'
----PRICE_BY_SUPPLIER----
PRODUCT_ID SUPPLIER_ID PRICE
1 1 10
1 2 9
1 3 9.5
2 1 5
----IMAGES_BY_Product----
PRODUCT_ID NAME
1 'pencil.img'
1 'pen.img'
1 'pencil_other.img'
2 'paper.img'
我想要一个查询来提取最低价格、供应商数量持有产品和一张图片(所有供应商中一张图片)。输出查询应如下所示:
----FINAL_QUERY----
PRODUCT_ID MIN_PRICE IMAGE SUPPLIER_COUNT
1 9 'pencil.img' 3
2 5 'paper.img' 1
我有这个查询,它返回除图像之外的所有内容。
SELECT f.PRODUCT_ID, f.DESC, x.MIN_PRICE, x.SUPPLIER_COUNT
FROM (
SELECT pp.PRODUCT_ID,
MIN(pp.PRICE) AS MIN_PRICE,
COUNT(pp.PRODUCT_ID) AS SUPPLIER_COUNT
FROM PRICE_BY_SUPPLIER AS pp
GROUP
BY pp.PRODUCT_ID
)
AS x
INNER JOIN PRODUCT AS f
ON f.PRODUCT_ID = X.PRODUCT_ID
你能帮我完成我的查询吗?
I have the following three tables:
----PRODUCT----
PRODUCT_ID DESC
1 'Pencil'
2 'Paper'
----PRICE_BY_SUPPLIER----
PRODUCT_ID SUPPLIER_ID PRICE
1 1 10
1 2 9
1 3 9.5
2 1 5
----IMAGES_BY_PRODUCT----
PRODUCT_ID NAME
1 'pencil.img'
1 'pen.img'
1 'pencil_other.img'
2 'paper.img'
I would like a query that pull the minimum price, the count of supplier that hold the product and one image (one image among all suppliers). The output query should look like this:
----FINAL_QUERY----
PRODUCT_ID MIN_PRICE IMAGE SUPPLIER_COUNT
1 9 'pencil.img' 3
2 5 'paper.img' 1
I have this query that return everything except the image.
SELECT f.PRODUCT_ID, f.DESC, x.MIN_PRICE, x.SUPPLIER_COUNT
FROM (
SELECT pp.PRODUCT_ID,
MIN(pp.PRICE) AS MIN_PRICE,
COUNT(pp.PRODUCT_ID) AS SUPPLIER_COUNT
FROM PRICE_BY_SUPPLIER AS pp
GROUP
BY pp.PRODUCT_ID
)
AS x
INNER JOIN PRODUCT AS f
ON f.PRODUCT_ID = X.PRODUCT_ID
Can you help me complete my query ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
与其参与所有这些可怕的连接,你难道不能尝试一些类似的事情吗?
Rather than get involved with all those horrific joins, couldn't you try something like...
您可以添加另一个连接来获取图像。例如,每个产品 ID 的
max
图像:如果图像是可选的,请将
join
替换为outer join
。根据您的 DBMS,您还可以获取随机图像。例如,在 SQL Server 中,您可以用cross apply
替换连接:或者甚至直接在 select 子句中替换:
You could add another join to fetch an image. For example, the
max
image per productid:If the image is optional, replace the
join
with anouter join
. Depending on your DBMS, you can also fetch a random image. For example, in SQL Server, you could replace the join withcross apply
:Or even directly in the select clause:
试试这个:
我能够得到你的确切输出(除了供应商计数,因为这对我来说没有意义。如果可以的话,请进一步解释。
更新:
这是一种蹩脚的方式得到你想要的但是......它确实有效:
Try this:
I was able to get your exact output (other than the supplier_count as that didn't make sense to me. Please explain further if you could.
UPDATED:
This is kind of a lame way to get what you want but... It does work: