2

我有一个这样的查询:

SELECT
  t.type,
  SUM( t.external_account )
FROM
  u_contracts c,
  u_data u,
  u_transactions t
WHERE
  c.user_id = u.id
  AND t.contract_id = c.id
  AND t.nulled =0
  AND DATE (c.init_date) < DATE (u.dead)
  AND u.dead IS NOT NULL
  AND t.type != 'repay'
GROUP BY
  t.type;

现在这给了我想要的结果,但现在我想添加 ORDER BY 到它,但是通过特定的字段名称,如:

ORDER BY FIELD( t.type, 'type1', 'type2', ... )

但我不能将它插入到查询中。当我这样尝试时:

SELECT
  t.type,
  SUM( t.external_account )
FROM
  u_contracts c,
  u_data u,
  u_transactions t
WHERE
  c.user_id = u.id
  AND t.contract_id = c.id
  AND t.nulled =0
  AND DATE (c.init_date) < DATE (u.dead)
  AND u.dead IS NOT NULL
  AND t.type != 'repay'
ORDER BY
  FIELD( t.type, 'initial', 'commision', 'overpay', 'penalty', 'penalty2' )
GROUP BY
  t.type;

它给出了我的 sql 错误:

ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'GROUP BY t.type' at line 17

这样做的正确方法是什么?

4

1 回答 1

8

你只是有错误的顺序group byand order by;

...
ORDER BY
  FIELD( t.type, 'initial', 'commision', 'overpay', 'penalty', 'penalty2' )
GROUP BY
  t.type;

应该:

...
GROUP BY
  t.type
ORDER BY
  FIELD( t.type, 'initial', 'commision', 'overpay', 'penalty', 'penalty2' );
于 2012-10-03T11:43:34.353 回答