查询返回语法错误时的MySQL情况

时间:2014-06-11 06:08:38

标签: mysql

查询时这是非法的情况吗?

它返回一个错误,告诉我要检查在votes >= ( SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold FROM votes ) level T附近使用的正确语法。我在MySQL 5.0.83上运行我的数据库。

SELECT CASE WHEN (
SELECT vote_candidate, MAX(votes_above_the_threshold) votes
FROM (
SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
FROM vote_orders
WHERE vote_order = 1
GROUP BY vote_candidate
HAVING votes_above_the_threshold >= (
SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
FROM votes
)
) t
WHERE votes_above_the_threshold = (
SELECT MAX(votes_above_the_threshold)
FROM vote_orders
)
) votes >= (
SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
FROM votes
) level
THEN (level - original_votes)
ELSE 0
END redistribution

2 个答案:

答案 0 :(得分:1)

你有几个问题:

  • 您选择两列作为标量子查询 - >只选择您感兴趣的那个
  • 您正在提供别名"投票"对于标量子查询 - >删除别名
  • 同样,你有一个"等级"稍后的标量子查询的别名 - >也删除这个

需要注意的是标量子查询只选择一个值没有别名

因此,我相信您正在寻找以下内容。请注意评论的差异:

SELECT CASE 
    WHEN (
        SELECT MAX(votes_above_the_threshold) votes
--           ^^^  *NOTE* removed "vote_candidate, "
        FROM (
            SELECT vote_candidate vote_candidate, COUNT(*) votes_above_the_threshold
            FROM vote_orders
            WHERE vote_order = 1
            GROUP BY vote_candidate
            HAVING votes_above_the_threshold >= (
                SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
                FROM votes
             )
        ) t
        WHERE votes_above_the_threshold = (
            SELECT MAX(votes_above_the_threshold)
            FROM vote_orders
        )
    ) >= (
--   ^^^ *NOTE* removed "votes" alias
        SELECT FLOOR((COUNT(*) / (2 + 1)) + 1) threshold
        FROM votes
    )
--   ^^^ *NOTE* removed "level" alias
THEN (level - original_votes)
ELSE 0
END redistribution

答案 1 :(得分:0)

您必须更改此部分:

WHERE votes_above_the_threshold = (
SELECT MAX(votes_above_the_threshold)
FROM vote_orders
)
) votes >= (

WHERE votes_above_the_threshold = (
SELECT MAX(votes_above_the_threshold)
FROM vote_orders
)
and votes >= (

这部分错了:

) level
THEN (level - original_votes)
ELSE 0
END redistribution

似乎缺少case when,但我不确定这意味着什么