MySql selecting default value if there are no results?

前端 未结 2 1330
有刺的猬
有刺的猬 2021-02-12 17:28

i\'m having 2 tables: members and comments. I select all members, and then join comments. But in comments I\'m selecting some SUM of points, and if user never commented, I can\'

相关标签:
2条回答
  • 2021-02-12 17:40

    MySQL has an IFNULL operator which allows you to return a value other than null if the result is null.

    SELECT c.comment_id AS item_id, m.member_id AS member_id, m.avatar, 
                SUM(IFNULL(c.vote_value, 0)) AS vote_value, SUM(IFNULL(c.best, 0)) AS best, 
                SUM(IFNULL(c.vote_value, 0)) + SUM(IFNULL(c.best, 0))*10 AS total
                FROM members m
                LEFT JOIN comments c ON m.member_id = c.author_id
                GROUP BY c.author_id
                ORDER BY m.member_id DESC
                LIMIT 0, 20
    

    As others mentioned, COALESCE does something similar (and also works in MySQL).

    0 讨论(0)
  • 2021-02-12 17:49

    I'm not sure why you are including the comment_id in your SELECT list if you just want users and their rankings. Do you want only their ranking on that particular comment? I'll give a solution for now that assumes you just want a full member list with rankings:

    SELECT
        M.member_id,
        M.user_id,
        M.avatar,
        COALESCE(SUM(C.vote_value), 0) AS vote_value_sum,
        COALESCE(SUM(C.best), 0) AS best_sum,
        COALESCE(SUM(C.vote_value), 0) + SUM(C.best) * 10 AS total_value
    FROM
        Members M
    LEFT OUTER JOIN Comments C ON
        C.author_id = M.member_id
    GROUP BY
        M.member_id
    ORDER BY
        total_value DESC
    LIMIT 0, 20
    

    (this assumes that vote_value and best are NOT NULL columns or that MySQL will disregard those when calculating SUM values - I believe that it does, but I haven't tested that)

    0 讨论(0)
提交回复
热议问题