这是我正在尝试使用的查询的精简版本:
SELECT user_id,
(SELECT COUNT(*) FROM responses WHERE option_id = 1 AND poll_id = 1 AND pref = 1) /
(SELECT COUNT(*) FROM responses WHERE poll_id = 1 AND pref = 1) AS pref_percent,
(SELECT COUNT(*) FROM responses WHERE option_id = 1 AND poll_id = 1 ) /
(SELECT COUNT(*) FROM responses WHERE poll_id = 1) AS all_percent,
ABS(all_percent - pref_percent) AS deviation
FROM responses
GROUP BY user_id
ORDER BY deviation DESC
我收到此错误:'字段列表'中的未知列'all_percent'
显然,在构造另一个用户定义的列(“偏差”)时,我无法引用用户定义的列(“all_percent”)。
所以,我的问题是......我如何修改此查询以避免错误?
我真的希望将查询结果按偏差排序,而不是必须在PHP中完成这项工作。
答案 0 :(得分:2)
围绕当前查询包装外部查询:
SELECT user_id, pref_percent, all_percent, ABS(all_percent - pref_percent) AS deviation
FROM (SELECT user_id,
(SELECT COUNT(*) FROM responses WHERE option_id = 1 AND poll_id = 1 AND pref = 1) /
(SELECT COUNT(*) FROM responses WHERE poll_id = 1 AND pref = 1) AS pref_percent,
(SELECT COUNT(*) FROM responses WHERE option_id = 1 AND poll_id = 1 ) /
(SELECT COUNT(*) FROM responses WHERE poll_id = 1) AS all_percent
FROM responses
GROUP BY user_id
) t
ORDER BY deviation DESC
答案 1 :(得分:1)
您需要使用变量@var:=
例如......
... SELECT @var:= COUNT(*)FROM answers WHERE poll_id = 1)AS all_percent, ABS(@ var1 - @ var2)AS偏差......
答案 2 :(得分:0)
SELECT *
FROM (SELECT user_id,
(SELECT COUNT(1)
FROM responses
WHERE option_id = 1
AND poll_id = 1
AND pref = 1) / (SELECT COUNT(1)
FROM responses
WHERE poll_id = 1
AND pref = 1) AS pref_percent,
(SELECT COUNT(1)
FROM responses
WHERE option_id = 1
AND poll_id = 1) / (SELECT COUNT(1)
FROM responses
WHERE poll_id = 1) AS all_percent,
Abs(all_percent - pref_percent) AS deviation
FROM responses
GROUP BY user_id) t
ORDER BY t.deviation DESC