Mysql:在Union All查询中避免Null

时间:2013-08-15 10:56:41

标签: mysql sql union

请帮我解决这个问题。 当第二列与第一列相同时,我得到空值。

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

1 个答案:

答案 0 :(得分:3)

你对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;