Mysql 如何检查JOIN的结果是否为NULL?
以下是我的表格结构:Mysql 如何检查JOIN的结果是否为NULL?,mysql,sql,null,concat,Mysql,Sql,Null,Concat,以下是我的表格结构: -- categories +----+-------------+ | id | name | +----+-------------+ | 1 | political | | 2 | cultural | | 3 | social | | 4 | historical | +----+-------------+ -- tags +----+-------------+-----------+-------------+--
-- categories
+----+-------------+
| id | name |
+----+-------------+
| 1 | political |
| 2 | cultural |
| 3 | social |
| 4 | historical |
+----+-------------+
-- tags
+----+-------------+-----------+-------------+-----------------+
| id | name | parent_id | category_id | total_used_num |
+----+-------------+-----------+-------------+-----------------+
| 1 | president | NULL | 1 | 43 |
| 2 | society | NULL | 3 | 345 |
| 3 | Trump | 1 | 1 | 5 |
| 4 | book | 5 | 2 | 5473 |
| 5 | library | NULL | 2 | 433 |
+----+-------------+-----------+-------------+-----------------+
这是我的问题:
SELECT t1.name,
CONCAT(t2.name, ',', cat.name) t_p
FROM tags t1
LEFT JOIN tags t2
ON t1.parent_id = t2.id
INNER JOIN categories cat
ON t1.category_id = cat.id
ORDER BY total_used_num DESC,
t1.id
/* output
+----+-------------+--------------------------+
| 1 | president | NULL |
| 2 | society | NULL |
| 3 | Trump | president,political |
| 4 | book | library,cultural |
| 5 | library | NULL |
+----+-------------+--------------------------+
看到了吗?带有NULL
的CONCAT
的结果是NULL
。不管怎样,我怎样才能避免呢?我还想把逗号设为有条件的。如果两个字段都不是空的,那么逗号应该在那里。这是预期结果:
+----+-------------+--------------------------+
| 1 | president | political |
| 2 | society | social |
| 3 | Trump | president,political |
| 4 | book | library,cultural |
| 5 | library | cultural |
+----+-------------+--------------------------+
我该怎么做呢?只要使用concat\u ws()
:
您可以使用case语句。这是Oracle查询,您可以为MySQL修改:
SELECT t1.name,
(case when t2.name is not null then ( t2.name || ', ') else '' end) || cat.name
FROM tags t1
LEFT JOIN tags t2
ON t1.parent_id = t2.id
INNER JOIN categories cat
ON t1.category_id = cat.id
ORDER BY t1.total_used_num DESC,
t1.id ;
只要使用CASE WHEN语句,就可以得到预期的输出。 请参阅下面的代码
SELECT t1.name, (CASE
WHEN (t2.name IS NULL)
THEN cat.name
ELSE (CONCAT(t2.name, ',', cat.name))
END) AS t_p
FROM tags t1
LEFT JOIN tags t2
ON t1.parent_id = t2.id
INNER JOIN categories cat
ON t1.category_id = cat.id
你到底是谁?你有没有在不到一分钟的时间里读过我的问题?!你真的很棒。我印象深刻。
SELECT t1.name, (CASE
WHEN (t2.name IS NULL)
THEN cat.name
ELSE (CONCAT(t2.name, ',', cat.name))
END) AS t_p
FROM tags t1
LEFT JOIN tags t2
ON t1.parent_id = t2.id
INNER JOIN categories cat
ON t1.category_id = cat.id