0

表结构是这样的:

actions: int(10)
unlock: tinyint(1)
user_id: int(20)
name: varchar(50)

我有这样的疑问:

SELECT SUM(actions) AS "sum_actions", SUM(unlock) AS "sum_unlock", user_id, name 
 FROM mytable AS `Results` WHERE user_id != 0 GROUP BY user_id 
 ORDER BY sum_actions DESC LIMIT 0,300

这给出了#1064 - You have an error in your SQL syntax错误。

当我删除SUM(unlock) AS "sum_unlock"然后查询工作。所以我认为不可能对 TINYINT 求和。所以我改成了,COUNT(unlock) as "count_unlock"但这没有帮助。我不想将“解锁”表更改为 INT,因为它只有布尔值。如何计算每个 user_id 的总和的解锁表?

4

2 回答 2

1

unlock是保留字。试试这个:

SELECT SUM(actions) AS "sum_actions", SUM(`unlock`) AS "sum_unlock", user_id, name 
FROM mytable AS `Results`
WHERE user_id != 0
GROUP BY user_id 
ORDER BY sum_actions DESC
LIMIT 0,300

是保留字的列表。

于 2013-04-15T18:54:11.893 回答
0

您可以尝试SUM(CAST(unlock AS INT))将列视为INT列而不实际将其更改为INT列:

SELECT
    SUM(actions) AS "sum_actions",
    SUM(CAST(unlock AS INT)) AS "sum_unlock",
    user_id,
    name 
FROM
    mytable AS `Results`
WHERE
    user_id != 0
GROUP BY
    user_id,
    name
ORDER BY
    sum_actions DESC
LIMIT 0,300
于 2013-04-15T18:36:31.667 回答