为什么我没有得到我期望的价值?

时间:2014-01-10 14:27:41

标签: mysql sql

Here is a relevant SQLFiddle

查询:

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,
        IFNULL(SUM(l.Type = 'up'),0) AS Uplikes, 
        IFNULL(SUM(l.Type = 'down'),0) AS Downlikes,
        (IFNULL(SUM(l.Type = 'up'),0) - IFNULL(SUM(l.Type = 'down'),0)) AS SumLikes,
        SUM(f.Type = 'up') AS CountFavorites
    FROM News n 
    INNER JOIN Users u ON n.UserIdn = u.UserIdn 
    LEFT JOIN Likes l ON n.NewsIdn = l.NewsIdn
    LEFT JOIN Favorites f ON n.NewsIdn = f.NewsIdn

    GROUP BY n.id 

我认为我的问题是值CountFavorites - 对于NewsIdn我得到的值= 2我期待1。

图片结果(http://i.stack.imgur.com/NqD9u.jpg):

enter image description here

任何人都可以帮我弄清楚为什么我的结果不符合预期?

1 个答案:

答案 0 :(得分:-1)

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,
            IFNULL(SUM(l.Type = 'up'),0) AS Uplikes, 
            IFNULL(SUM(l.Type = 'down'),0) AS Downlikes,
            (IFNULL(SUM(l.Type = 'up'),0) - IFNULL(SUM(l.Type = 'down'),0)) AS SumLikes,
            (select count(*) from favorites f where f.Type = 'up' and n.NewsIdn = f.NewsIdn) AS CountFavorites
        FROM News n 
        INNER JOIN Users u ON n.UserIdn = u.UserIdn 
        LEFT JOIN Likes l ON n.NewsIdn = l.NewsIdn
        -- LEFT JOIN Favorites f ON n.NewsIdn = f.NewsIdn

        GROUP BY       n.Type, n.UserIdn,u.Username,n.NewsIdn,Header,n.Text,n.Tags ,n.ImageLink, n.VideoLink , n.DateCreate

你的错误是加入一对多,复制行。如果您在多次连接之后使用聚合,那么您将遇到不好的时间。聚合之前加入这些情况。

或者你可以把它写成

            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,
              Uplikes, 
             Downlikes,
            SumLikes,
 CountFavorites
inner join users on ...
left join (
select l.news_idn, 
IFNULL(SUM(l.Type = 'down'),0) AS Downlikes,
(IFNULL(SUM(l.Type = 'up'),0) - IFNULL(SUM(l.Type = 'down'),0)) AS SumLikes
from likes) l
on n.NewsIdn = l.NewsIdn

left join (select newsidn ,count(*) CountFavorites from favorites f where f.Type = 'up') f on i.newsidn=n.newsidn