2016-12-16 6 views
0

バリエーションとしてthis questionを2つインターリーブし、グループ化し、どちらのテーブルの値がか、そのうち2つのSQLテーブル、グループをインターリーブし、どのテーブルから来たかを知るまたは両方

例えば

...

mysql> select id, date from events order by date; 
+----+------------+ 
| id | date  | 
+----+------------+ 
| 1 | 2016-08-01 | 
| 6 | 2016-08-01 | 
| 4 | 2016-08-03 | 
| 2 | 2016-08-05 | 
| 5 | 2016-08-05 | 
| 3 | 2016-08-11 | 
+----+------------+ 

mysql> select id, date from posts order by date; 
+----+------------+ 
| id | date  | 
+----+------------+ 
| 1 | 2016-08-03 | 
| 2 | 2016-08-05 | 
| 4 | 2016-08-05 | 
| 3 | 2016-08-07 | 
+----+------------+ 

私はこれをしたいと思います。

+------------+-------+ 
| date  | type | 
+------------+-------+ 
| 2016-08-01 | event | 
| 2016-08-03 | both | 
| 2016-08-05 | both | 
| 2016-08-07 | post | 
| 2016-08-11 | event | 
+------------+-------+ 

これは私が持っているものであり、動作します。それがよりうまくいくかどうか疑問に思います。 caseだけでなく、union allもあります。行が一つのテーブルまたは他から来なければならない、すべての後

select t.date as date, 
     (case when max(which) = min(which) then max(which) 
      else 'both' 
     end) as type 
from ((select date, 'event' as which from events 
    ) union all 
     (select date, 'post' as which from posts 
    ) t 
group by t.date 
order by t.date; 

select things.date as date, 
     case bit_or(type) 
     when 1 then "event" 
     when 2 then "post" 
     when 3 then "both" 
     else "unknown" 
     end as type 
from (select date, 1 as type from events 
       union all 
     select date, 2 as type from posts 
    ) things 
group by things.date 
order by things.date 

答えて

2

は、私が何かは、両方から来たかどうかを判断するためにシンプルなロジックがあると思います。​​は必要ありません。

+0

両方ともあなたのcase文で 'both'です。私は 'else which'だと思う。 – GurV

+0

@ GurwinderSingh。 。 。ありがとうございました。最初は 'then max(which)'または '' min(which) 'でなければなりません。 –

関連する問題