我有一个产生正确结果的查询,它只是非常慢。我觉得必须有更好的方法(也许没有子查询)。
表,结果和查询如下。我已经对数据进行了匿名处理,我有8个子查询而不是2个,但格式是相同的。
id userId type amount
------------------------------------
1 1 a 400
2 1 b 300
3 1 c 230
4 2 a 600
5 2 b 500
6 2 c 430
我在每列上都有一个索引,另外一个包含userId和type列。我还可以保证userId和type是唯一的(即用户1不会有两个'a'类型。)
期望的结果:
userId typeAtotal typeBtotal
--------------------------------
1 400 300
2 600 500
我的查询:
SELECT userId,
(SELECT amount
FROM a AS a2
WHERE a2.userId = a1.userId
AND a2.type = 'a') AS aAmt,
(SELECT amount
FROM a AS a3
WHERE a3.userId = a1.userId
AND a3.type = 'b') AS bAmt
FROM a AS a1
WHERE type IN ('a','b')
GROUP BY userId
答案 0 :(得分:5)
使用:
SELECT t.userid,
MAX(CASE WHEN t.type = 'a' THEN amount ELSE NULL END) AS typeAtotal,
MAX(CASE WHEN t.type = 'b' THEN amount ELSE NULL END) AS typeBtotal
FROM YOUR_TABLE t
GROUP BY t.userid
如果任何一种类型都有多个金额 - 这将返回最高金额。如果您想要添加此类情况,请使用SUM
:
SELECT t.userid,
SUM(CASE WHEN t.type = 'a' THEN amount ELSE NULL END) AS typeAtotal,
SUM(CASE WHEN t.type = 'b' THEN amount ELSE NULL END) AS typeBtotal
FROM YOUR_TABLE t
GROUP BY t.userid
答案 1 :(得分:1)
看起来像我的交叉制表。您可以尝试这样的事情:
SELECT userId,
SUM(IF(a.type = 'a'), a.amount, 0) AS aAmount,
SUM(IF(a.type = 'b'), a.amount, 0) AS bAmount
FROM a
WHERE type IN ('a', 'b')
GROUP BY a.userId
您可能希望阅读这篇写得很好的教程:http://dev.mysql.com/tech-resources/articles/wizard/index.html
编辑:修正了ELSE条件。