首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >连接2个字段相同但不重复的表

连接2个字段相同但不重复的表
EN

Stack Overflow用户
提问于 2018-05-23 17:53:12
回答 1查看 14关注 0票数 0

我有2个表与相同的行-我需要将这些表附加到两行(产品和vint),出价的id不应该重复的出价和订单,如果它已经是然后需要NULL。

代码语言:javascript
复制
SELECT b.product, b.vint, o.id as offer_id, b.id as bid_id from bids b LEFT 
JOIN offers o ON b.product = o.product AND o.vint=b.vint group by 
b.product, b.vintage, b.id
 UNION
SELECT o.product, o.vint, o.id as offer_id, b.id as bid_id from bids b RIGHT 
JOIN offers o ON b.product = o.product AND o.vint=b.vint group 
by o.product, o.vint, o.id

示例:我们需要:

代码语言:javascript
复制
 product    |   vint  |  bid_id | offer_id
 Pro_1      |    s12  |   1     |   3
 Pro_2      |    s13  |   2     |   NULL
 Pro_1      |    s13  |   4     |   1
 Pro_2      |    s11  |   NULL  |   2
 Pro_3      |    s10  |   5     |   4

但我的结果是:

代码语言:javascript
复制
product     |   vint  |  bid_id | offer_id
Pro_1       |    s12  |   1     |   3
Pro_2       |    s13  |   2     |   1
Pro_1       |    s13  |   4     |   1
Pro_2       |    s11  |   NULL  |   2
Pro_3       |    s10  |   5     |   4
Pro_1       |    s12  |   1     |   NULL
EN

回答 1

Stack Overflow用户

发布于 2018-05-23 18:07:37

我认为在像这样的联合2表之后,你应该再按bid_id分组一次。

代码语言:javascript
复制
select * from (
   SELECT b.product, b.vint, MAX(o.id) as offer_id, MIN(b.id)  as bid_id from 
   bids b LEFT JOIN offers o ON b.product = o.product AND o.vint=b.vint group 
   by b.product, b.vintage, b.id
     union 
   SELECT o.product, o.vint, MIN(o.id) as offer_id, MAX(b.id)  as 
   bid_id from bids b RIGHT JOIN offers o ON b.product = o.product AND 
   o.vint=b.vint group by o.product, o.vint, o.id
) as demo_table group by bid_id
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50485181

复制
相关文章

相似问题

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