jpa+mysql,union組合查詢求和結果出錯
阿新 • • 發佈:2019-02-13
UNION ALL
有兩個表,A和B。
A表資料類似
id | a1 | a2 | a3 | a4 | a5 |
1 | 5 | 0.5 | a | g1 | ... |
2 | 10 | 1.0 | a | g2 | ... |
3 | 15 | 1.5 | a | g1 | ... |
B表資料類似
id | a1 | a2 | a3 | a4 | a5 |
1 | 10 | 2 | b | g2 | ... |
2 | 20 | 4 | b | g1 | ... |
3 | 30 | 6 | b | g1 | ... |
結果發現,sum(x)結果是對的,但sum(y)是錯的,為什麼呢?SELECT count(*), sum(x),sum(y),z,w FROM ( (SELECT a1 as x, a2 as y, a3 as z, a4 as w FROM A) UNION ALL (SELECT b1 as x, b3 as z, b2 as y, b4 as w FROM B) )t GROUP BY w
因為按照我的思路,UNION的select結果應該是:
x | y | z | w |
5 | 0.5 | a | g1 |
10 | 1.0 | a | g2 |
15 | 1.5 | a | g1 |
10 | 2 | b | g2 |
20 | 4 | b | g1 |
30 | 6 | b | g1 |
但實際上結果卻是:
x | y | z | w |
5 | 0.5 | a | g1 |
10 | 1.0 | a | g2 |
15 | 1.5 | a | g1 |
10 | b | 2 | g2 |
20 | b | 4 | g1 |
30 | b | 6 | g1 |
注意:y下面的三行不是數字,而是字母。
這時來看上面被union的兩個select的欄位順序,
第一個是:a1,a2,a3,a4,
第二個是:b1,b3,b2,b4,
雖然其對應的xyzw都沒對應錯,但是:
union查詢時並不會按你為各欄位起的別名進行一一對應,而是按你的select時的欄位順序進行對應的