MySQL在同一表上左联接,结果翻倍

时间:2019-04-24 10:23:03

标签: mysql join left-join outer-join

我有这张桌子:

  

项目|时间戳|值
x | 1 | 30
x | 2 | 40
x | 3 |   50
y | 1 | 25
y | 3 | 15

我想得到他的结果:

  

时间戳| xval | yval
1 | 30 | 25
3 | 50 | 15
2 | 40   | NULL

但是通过此查询,我得到了双重不必要的结果:

select x.timestamp, x.value as xval, y.value as yval from test x left join test y on x.timestamp=y.timestamp and x.item!=y.item

结果是:

  

时间戳| xval | yval
1 | 25 | 30
3 | 15 | 50
1 | 30   | 25
3 | 50 | 15
2 | 40 | NULL

我想要一个没有前两行的结果。

1 个答案:

答案 0 :(得分:3)

基本的数据透视查询应在此处工作:

SELECT
    timestamp,
    MAX(CASE WHEN item = 'x' THEN value ELSE NULL END) AS xval,
    MAX(CASE WHEN item = 'y' THEN value ELSE NULL END) AS yval
FROM test
GROUP BY
    timestamp
ORDER BY
    timestamp;

enter image description here

Demo