1

これを解決するのを手伝ってください。2番目の列に1番目の列と同じ方法で結果がある場合、null値を取得しています。

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
4

1 に答える 1

3

あなたは何をするかについて強い誤解を持ってunion allいます。あなたのselect声明:

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

常にNULL少なくとも 1 つの列に返されます。

列を揃えたいようです。まず、次のクエリで十分かどうかお尋ねします。

  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;

リストを 2 列に揃えることは、SQL の得意分野ではありません (可能ですが、簡単ではありません)。したがって、別の解決策がある場合は、それを選択してください。

編集:

必要なものを取得するには、2 つのリストの行番号が必要です。持っていないので、変数を使用して作成する必要があります。

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;
于 2013-08-15T11:03:12.193 に答える