MySql selecting default value if there are no results?

前端 未结 2 1337
有刺的猬
有刺的猬 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).

提交回复
热议问题