我有2个相同行的表 - 我需要将这些表附加到两行(产品和vint),并且出价的ID不应该在出价中重复,如果已经是然后需要NULL。
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
实施例: 我们需要:
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
但我的结果是:有重复
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
答案 0 :(得分:0)
我认为你应该在这样的工会2表之后再按bid_id分组。
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