MySQL多列匹配多行结果

问题描述 投票:0回答:2

我是mySQL的新手,并尝试解决这一天。我尝试将来自Want1列的数据与Offer1匹配,并将Want2与Offer2匹配,但Type也需要与其他uid匹配。每个uid在W / O中只有W或O(想要/提供)。这是我的桌子。

用户表:

Id,  Want1, Want2, Offer1, Offer2, Type, uid, W/O
---  -----  -----  ------  ------  ----  ---  ---
1      a     null   null    null    KK    5    W
2    null      b    null    null    LL    30   W
3    null    null     a     null    KK    20   O
4    null    null   null      b     LL    13   O
5    null    null     a     null    BB    6    O
6    null    null     a     null    KK    70   O

所需的表结果:

Want1, Want2, Offer1, Offer2, Type, uidW, uidO
-----  -----  ------  ------  ----  ----  ----
 a      null     a     null    KK     5    20
 null     b     null     b      LL    30    13
 a      null     a     null    KK     5    70

是否可以使用纯SQL来获得此结果?

mysql sql database
2个回答
0
投票

这是一个解决方案

SELECT w.want1,
       w.want2,
       o.offer1,
       o.offer2,
       w.Type,
       w.uid AS uidW,
       o.uid AS uidO
  FROM my_table w LEFT JOIN
       my_table o ON (IFNULL(w.want1, 'x') = IFNULL(o.offer1, 'x') AND
                       IFNULL(w.want2, 'x') = IFNULL(o.offer2, 'x') AND
                       w.type = o.type)
 WHERE w.wo = 'W' AND
       o.wo = 'O';

产量

want1   want2   offer1  offer2  Type    uidW    uidO
a   (null)  a   (null)  KK  5   20
(null)  b   (null)  b   LL  30  13
a   (null)  a   (null)  KK  5   70

在这里演示 - http://sqlfiddle.com/#!9/e1ff2e/20


0
投票

对于您的特定数据:

select max(want1), max(want2), max(offer1), max(offer2),
       max(case when `W/O` = 'W' then uid end) as UID_W,
       max(case when `W/O` = 'O' then uid end) as UID_O
from t
group by coalesce(want1, offer1), coalesce(want2, offer2), `W/O`;

这假设最后两行中的一行真的是'a', null, null

© www.soinside.com 2019 - 2024. All rights reserved.