首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Mysql自连接数据

Mysql自连接数据
EN

Stack Overflow用户
提问于 2016-09-15 15:47:11
回答 1查看 36关注 0票数 0

我有一张桌子

代码语言:javascript
复制
distributor_id | product_id | price
1              | 1          | 10.00
1              | 2          | 11.00
1              | 3          | 12.00
1              | 1          | 14.00
4              | 1          | 9.00
4              | 2          | 32.00
4              | 5          | 17.00

我想要比较分销商的产品价格,即我想得到如下的输出:

代码语言:javascript
复制
distributor1|distributor2|product_id|distributor1_price|distributor2_price
1           | 4          | 1        |12.00             |9.00
1           | 4          | 2        |11.00             |32.00
1           | 4          | 3        |12.00             |null

distributor1_price,distributor2_price将是product_id的平均价格。product_id应该是distributor1的所有产品。如果distributor2没有该产品,则应该为空。

我已经尝试了self-join,但没有成功。谢谢。

EN

回答 1

Stack Overflow用户

发布于 2016-09-15 15:57:58

还没有测试过,但我认为这应该是可行的:

代码语言:javascript
复制
SELECT a.distributor_id
    ,b.distributor_id
    ,a.product_id
    ,AVG(a.price)
    ,AVG(b.price)
FROM mytable AS a
LEFT JOIN mytable AS b ON a.product_id = b.product_id
GROUP BY a.product_id
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/39505627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档