mysql - 如何判断JOIN的结果是否为NULL?

标签 mysql sql null concatenation

这是我的表结构:

-- 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                     |
+----+-------------+--------------------------+

看到了吗? CONCATNULL 的结果是 NULL。无论如何,我怎样才能避免这种情况呢?我还想将逗号 , 作为条件。如果两个字段都不为 NULL,则该逗号应该存在。这是预期结果:

+----+-------------+--------------------------+
| 1  | president   | political                |
| 2  | society     | social                   |
| 3  | Trump       | president,political      |
| 4  | book        | library,cultural         |
| 5  | library     | cultural                 |
+----+-------------+--------------------------+

我怎样才能做到这一点?

最佳答案

只需使用concat_ws():

SELECT t1.name, 
       CONCAT_WS(',', t2.name, cat.name) 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 
ORDER BY total_used_num DESC, t1.id ;

关于mysql - 如何判断JOIN的结果是否为NULL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45025521/

相关文章:

php - 使用 php 将希伯来语 utf8 保存到数据库

java - 我想使用连接池,但我的 java 应用程序不是 servlet

php - 如何从 php 进行的 SQL 查询中获取值?

mysql - 有没有办法使用 MYSQL 在 CASE 语句 THEN 部分中执行多项操作?

sql - 如何联合 SELECT 两个具有两个表的 ID 的表?

sql - 如何创建一个没有数据的重复表

ios - Swift - 在图像中展开 NSdata 的可选值时意外发现 nil

MySQL:何时分解/分割表

SQL Server 2008 存储过程 - 优化器认为我的参数可以为空

oracle - 如何验证空值 - oracle etl 测试?