我怎样才能替换null?

时间:2016-07-10 14:06:54

标签: mysql sql

我有两张这样的表:

// users
+----+--------+------------+----------------+------------+
| id |  name  | reputation |     avatar     | visibility |
+----+--------+------------+----------------+------------+
| 1  | John   | 344        | er0942334r4... | 1          |
| 2  | Peter  | 65544      | 340ojfc343f... | 0          |
+----+--------+------------+----------------+------------+

// posts
+----+--------+------------+-----------+
| id | title  |  content   | author_id |
+----+--------+------------+-----------+
| 1  | title1 | content1   | 2         |
| 2  | title2 | content2   | 1         |
+----+--------+------------+-----------+

这也是我的疑问:

SELECT p.*, u.name, u.reputation rep, u.avatar
FROM posts p
LEFT JOIN users u
ON u.id = p.author_id AND u.visibility = 1
// please focus on this-> ^^^^^^^^^^^^^^^^

这是当前结果:

+----+--------+------------+-----------+--------+------+----------------+
| id | title  |  content   | author_id |  name  | rep  |     avatar     |
+----+--------+------------+-----------+--------+------+----------------+
| 1  | title1 | content1   | 2         |        |      |                |
| 2  | title2 | content2   | 1         | John   | 344  | er0942334r4... |
+----+--------+------------+-----------+--------+------+----------------+

现在我想在visibility <> 1name or rep or avatar is null时设置一些默认值。所以这是预期的结果:

+----+--------+------------+-----------+--------+------+----------------+
| id | title  |  content   | author_id |  name  | rep  |     avatar     |
+----+--------+------------+-----------+--------+------+----------------+
| 1  | title1 | content1   | 2         | NoName | 1    | default        |
| 2  | title2 | content2   | 1         | John   | 344  | er0942334r4... |
+----+--------+------------+-----------+--------+------+----------------+

我该怎么做?

注意:我可以通过PHP这样做:

$name = is_null($result['name'])   ? 'NoName'  : $result['name'];
$name = is_null($result['rep'])    ? 1         : $result['rep'];
$name = is_null($result['avatar']) ? 'default' : $result['avatar'];

但我想知道如何通过 pure sql 来实现这一点。

1 个答案:

答案 0 :(得分:1)

您只需使用COALESCE()

即可
SELECT p.*,
       COALESCE(u.name,'NoName') as `name`,
       COALESCE(u.reputation,1) as rep,
       COALESCE(u.avatar,'default') as avatar
FROM posts p
LEFT JOIN users u
ON u.id = p.author_id AND u.visibility = 1

您也可以将其替换为IFNULL。它们之间的区别在于COALESCE()可以处理多个参数。