开发者

MySQL: Order by absolute value of user-defined columns

开发者 https://www.devze.com 2023-02-17 18:01 出处:网络
Here\'s a stripped-down version of a query I\'m trying to use: SELECT user_id, (SELECT COUNT(*) FROM responses WHERE option_id = 1 AND poll_id = 1 AND pref = 1) /

Here's a stripped-down version of a query I'm trying to use:

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 开发者_JAVA百科= 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

I get this error: Unknown column 'all_percent' in 'field list'

Apparently, I can't reference a user-defined column ("all_percent") when constructing another user-defined column ("deviation").

So, my question is ... how might I modify this query to avoid the error?

I'd really like to have the query results sorted by deviation, rather than having to do that work in PHP.


Wrap an outer query around your current query:

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


You need to use a variable @var:=

for eg..

...SELECT @var := COUNT(*) FROM responses WHERE poll_id = 1) AS all_percent, ABS(@var1 - @var2) AS deviation...


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 
0

精彩评论

暂无评论...
验证码 换一张
取 消