Mysql:避免Union All查询中的空值

标签 mysql sql union

请帮我解决这个问题。 当第 2 列以与第 1 列相同的方式产生结果时,我得到空值。

select 
   (case when parents  = '3' then child end) 3_rec,
   (case when parents  = '10' then child end) 10_rec
from
(
  SELECT concat(a.name,' (',b.count,')') as child,b.parent as parents FROM wp_terms a,wp_term_taxonomy b where 
a.term_id=b.term_id and b.parent = 3 and b.taxonomy = 'category'
  union all
  SELECT concat(a.name,' (',b.count,')') as child,b.parent as parents FROM wp_terms a,wp_term_taxonomy b where 
a.term_id=b.term_id and b.parent = 10 and b.taxonomy = 'category'
) d order by 1,2 asc

我期待的结果。Null 应该排在最后。

3_rec|10_rec
------------
row1 | row1
row2 | row2
row3 | row3
     | row4
     | row5

最佳答案

你对 union all 的作用有很大的误解。您的 select 语句:

select (case when parents  = '3' then child end) 3_rec,
      (case when parents  = '10' then child end) 10_rec

总是至少在其中一列中返回NULL

您似乎想要对齐列。首先,我会问以下查询是否足以满足您的需求:

  SELECT concat(a.name,' (',b.count,')') as child,b.parent as parents
  FROM wp_terms a join
       wp_term_taxonomy b 
       on a.term_id=b.term_id
  WHERE b.parent in (3, 10) and b.taxonomy = 'category'

这将返回单独行上的值。或者,您可以:

  SELECT b.parent,
         group_concat(concat(a.name,' (',b.count,')'), ';') as children
  FROM wp_terms a join
       wp_term_taxonomy b 
       on a.term_id=b.term_id
  WHERE b.parent in (3, 10) and b.taxonomy = 'category'
  group by p.parent;

在两列中对齐列表不是 SQL 的强项(可能,但并不容易)。因此,如果有其他解决方案,那就去做吧。

编辑:

要得到你想要的,你需要两个列表的行号。你没有,所以你必须用变量创建一个。

select max(case when parent = 3 then child end) as "3_child",
       max(case when parent = 10 then child end) as "10_child"
from (SELECT concat(a.name,' (',b.count,')') as child, b.parent as parents,
             @rn := if(@parent = b.parent, @rn + 1, 1) as rn,
             @parent := b.parent
      FROM wp_terms a join
           wp_term_taxonomy b 
           on a.term_id=b.term_id cross join
           (select @rn := 0, @parent := '') const
      WHERE b.parent in (3, 10) and b.taxonomy = 'category'
      order by b.parent
     ) t
group by rn
order by rn;

关于Mysql:避免Union All查询中的空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18251275/

相关文章:

mysql - 如何在 mysql UNION 查询中编写这个 GROUP BY

php - MySQL 查询 CASE 或 JOIN 或 UNION - 使用哪个?

php - 重新排列 MySQLi 查询的数组结果

mysql - SQL跨表索引的方法?

sql - .verify.JDBC.result(r, "Unable to retrieve JDBC result set",: Unable to retrieve JDBC result set JDBC ERROR: Numeric value 'NA' is not 中的错误

mysql - SQL 中 VARCHAR(x) 和 VARCHAR(y) 的区别

c# - MySqlDataReader - 阅读器关闭时尝试读取无效

php - 创建表

Java 如何在Java中为SQLITE创建查询队列以防止数据丢失?

scala - Spark union 因嵌套 JSON 数据帧而失败