交错两个SQL表,组,并知道它来自哪个表或两个

时间:2016-12-16 03:30:56

标签: mysql

作为this question的变体,我希望交换两个表,分组依据,并知道值来自哪个表,或者它是否来自两个

例如......

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

1 个答案:

答案 0 :(得分:2)

我认为有一个更简单的逻辑可以确定是否来自两者:

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;

毕竟,一行必须来自一个表或另一个表。 bit_or()并非必要。