MySQL多列匹配多行结果

时间:2017-12-23 19:19:55

标签: mysql sql database

我是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来获得此结果?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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