3
SELECT语句的结果与VIEW中的SELECT结果不同。如何解决问题并从视野中获得相同的结果?不同的SELECT和VIEW中的SELECT结果
动作表:
+--+---------+--------------+-----------+------+
|id|person_id|action_type_id|currency_id|sum |
+--+---------+--------------+-----------+------+
|1 |1 |1 |1 | 1.00 |
|2 |1 |1 |1 | 5.00 |
|3 |1 |1 |2 |10.00 |
|4 |1 |2 |1 | 2.00 |
|5 |2 |1 |1 |20.00 |
|6 |2 |2 |2 | 5.00 |
+--+---------+--------------+-----------+------+
选择:
SELECT person_id AS p, currency_id AS c,
(
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=1 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2)) -
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=2 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2))
) AS sum
FROM actions
GROUP BY currency_id, person_id
ORDER BY person_id, currency_id;
结果:
+--+--+------+
|p |c |sum |
+--+--+------+
|1 |1 | 4.00 |
|1 |2 |10.00 |
|2 |1 |20.00 |
|2 |2 |-5.00 |
+--+--+------+
选择内部视图:
CREATE VIEW p_sums AS
SELECT person_id AS p, currency_id AS c,
(
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=1 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2)) -
CAST(
COALESCE(
(SELECT SUM(sum) FROM actions WHERE action_type_id=2 AND person_id=p AND currency_id=c)
, 0)
AS DECIMAL(11,2))
) AS sum
FROM actions
GROUP BY currency_id, person_id
ORDER BY person_id, currency_id;
SELECT * FROM p_sums;
结果:
+--+--+------+
|p |c |sum |
+--+--+------+
|1 |1 |29.00 |
|1 |2 |29.00 |
|2 |1 |29.00 |
|2 |2 |29.00 |
+--+--+------+
你使用的是哪个版本的mysql? – Jason 2011-01-06 13:17:06
只是FYI,对于新手(我也是一个),当有人帮助提供解决方案时,它是让你超越你的残局的一种方法,点击他们答案下的复选框可以让他们相信,以便其他人知道解决方案已经解决。 – DRapp 2011-01-06 13:29:43