如何正确执行查询?

时间:2014-01-10 11:30:23

标签: mysql sql select group-by having

STRUCTURE TABLES AND ERROR WHEN EXECUTE QUERY ON SQLFIDDLE

QUERY:

SELECT 
            n.Type as Type,
            n.UserIdn as UserIdn,
            u.Username as Username,
            n.NewsIdn as NewsIdn,
            n.Header as Header,
            n.Text as Text,
            n.Tags as Tags,
            n.ImageLink as ImageLink,
            n.VideoLink as VideoLink,
            n.DateCreate as DateCreate,
            SUM(l.Type = 'up') as Uplikes, 
            SUM(l.Type = 'down') as Downlikes,
            (SUM(l.Type = 'up') - SUM(l.Type = 'down')) as SumLikes
        FROM News n 
            INNER JOIN Users u ON n.UserIdn = u.UserIdn 
            LEFT JOIN Likes l ON n.NewsIdn = l.NewsIdn
            WHERE SumLikes > 20 AND n.DateCreate < STR_TO_DATE('2014-01-03 14:17:43', '%Y-%m-%d %H:%i:%s')
        GROUP BY n.id
        ORDER by SumLikes DESC

当我使用查询时,我收到错误:

Unknown column 'SumLikes' in 'where clause'...

我知道'SumLikes'中的错误但是如何正确地进行sql查询?

请告诉我怎么做?

4 个答案:

答案 0 :(得分:1)

你不能在where子句中使用像sum()这样的聚合字段,你可以使用having

您的查询结尾可能是:

GROUP BY n.id
HAVING SumLikes > 20
ORDER by SumLikes DESC

ofcourse删除SumLikes > 20中的where

查看此信息以获取更多信息:MySQL Extensions to GROUP BY

答案 1 :(得分:1)

在为列添加别名时,我们需要不同地解决它。

删除SumLikes > 20 并在GROUP BY

之后添加一个额外的命令

示例:

HAVING SumLikes > 20

答案 2 :(得分:0)

将其包装在子查询中

SELECT * FROM
(
SELECT 
    n.Type as Type,
    n.UserIdn as UserIdn,
    u.Username as Username,
    n.NewsIdn as NewsIdn,
    n.Header as Header,
    n.Text as Text,
    n.Tags as Tags,
    n.ImageLink as ImageLink,
    n.VideoLink as VideoLink,
    n.DateCreate as DateCreate,
    SUM(l.Type = 'up') as Uplikes, 
    SUM(l.Type = 'down') as Downlikes,
    (SUM(l.Type = 'up') - SUM(l.Type = 'down')) as SumLikes
FROM News n 
    INNER JOIN Users u ON n.UserIdn = u.UserIdn 
    LEFT JOIN Likes l ON n.NewsIdn = l.NewsIdn
    WHERE n.DateCreate < STR_TO_DATE('2014-01-03 14:17:43', '%Y-%m-%d %H:%i:%s')
GROUP BY n.id
) Sub
WHERE Sub.SumLikes > 20
ORDER by Sub.SumLikes DESC

答案 3 :(得分:0)

试试这个:

SELECT 
    n.Type AS TYPE,
    n.UserIdn AS UserIdn,
    u.Username AS Username,
    n.NewsIdn AS NewsIdn,
    n.Header AS Header,
    n.Text AS TEXT,
    n.Tags AS Tags,
    n.ImageLink AS ImageLink,
    n.VideoLink AS VideoLink,
    n.DateCreate AS DateCreate,
    SUM(l.Type = 'up') AS Uplikes, 
    SUM(l.Type = 'down') AS Downlikes,
    (SUM(l.Type = 'up') - SUM(l.Type = 'down')) AS SumLikes
FROM News n 
INNER JOIN Users u ON n.UserIdn = u.UserIdn 
LEFT JOIN Likes l ON n.NewsIdn = l.NewsIdn
WHERE n.DateCreate < '2014-01-03 14:17:43'
GROUP BY n.id HAVING SumLikes > 20 
ORDER BY SumLikes DESC