如何从表左边的列加入?

时间:2014-01-08 14:36:22

标签: mysql

SqlFidle here.

Mysql查询:

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,
            l.Uplikes as Uplikes,
            ld.DownLikes as DownLikes
        FROM News n 
            left join (Select LikeIdn,NewsIdn,Count(*) as UpLikes FROM Likes WHERE Type='up') as l ON l.NewsIdn=n.NewsIdn
            left join (Select LikeIdn,NewsIdn,Count(*) as DownLikes FROM Likes WHERE Type='down') as ld ON ld.NewsIdn=n.NewsIdn
            left join Users u on u.UserIdn = n.UserIdn
            WHERE (l.Uplikes - ld.DownLikes) < 20 AND DateCreate < STR_TO_DATE('2014-01-01 17:23:41', '%Y-%m-%d %H:%i:%s')
        ORDER BY n.DateCreate Desc LIMIT 0, 10

在查询中,我无法获得l.Uplikes as Uplikesld.DownLikes as DownLikes

如何获得它?

P.S。:如果删除行(l.Uplikes - ld.DownLikes) < 20 AND结果查询有4行。

2 个答案:

答案 0 :(得分:1)

问题是left outer join正在为NULLlikes插入dislikes值。因此,使用coalesce()将它们转换为0:

        WHERE (coalesce(l.Uplikes, 0) - coalesce(ld.DownLikes, 0)) < 20 AND
              DateCreate < STR_TO_DATE('2014-01-01 17:23:41', '%Y-%m-%d %H:%i:%s')

顺便说一句,有很多方法可以编写此查询。但是,您的版本不正确。在两个子查询中需要group by NewsIdn。否则,你会得到总的喜欢和不喜欢。但是,两个子查询也是不必要的。您可以使用条件聚合一步计算likesdislikes,而不是两个:

    FROM News n left join
         (Select NewsIdn, sum(Type = 'up') as UpLikes,  sum(Type = 'down') as dislikes
          FROM Likes
          group by NewsIdn
         ) ud
         ON ud.NewsIdn = n.NewsIdn left join
         Users u
         on u.UserIdn = n.UserIdn

答案 1 :(得分:0)

是的,因为您已经注意到它是因为您在where子句中使用UplikesDownLikes的值,并且您在您喜欢的表中没有相应的行(所以你得到null而不是比0)。

如果你在where子句中合并为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,
        COALESCE(l.Uplikes,0) as Uplikes,
        COALESCE(ld.DownLikes,0) as DownLikes
    FROM News n 
        left join (Select LikeIdn,NewsIdn,Count(*) as UpLikes FROM Likes WHERE Type='up' Group by NewsIdn) as l ON l.NewsIdn=n.NewsIdn
        left join (Select LikeIdn,NewsIdn,Count(*) as DownLikes FROM Likes WHERE Type='down' Group by NewsIdn) as ld ON ld.NewsIdn=n.NewsIdn
        left join Users u on u.UserIdn = n.UserIdn
        WHERE (COALESCE(l.Uplikes,0) - COALESCE(ld.DownLikes,0) < 20) AND DateCreate < STR_TO_DATE('2014-01-01 17:23:41', '%Y-%m-%d %H:%i:%s')
    ORDER BY n.DateCreate Desc LIMIT 0, 10

或者如果它更容易:

Sql fiddle

修改: +1给Gordon Linoff注意到子查询中缺少的分组 - 更新了这个答案以反映出来。