gpt4 book ai didi

mysql - 我怎样才能替换空值?

转载 作者:行者123 更新时间:2023-11-28 23:28:28 25 4
gpt4 key购买 nike

我有两个这样的表:

// 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 <> 1 时设置一些默认值或 name 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'];

但我想知道如何通过纯 sql 做到这一点。

最佳答案

您可以简单地使用 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() 可以处理多个参数。

关于mysql - 我怎样才能替换空值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38292759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com