我如何合并这两个选择语句?

时间:2013-01-30 16:49:25

标签: mysql

我有2个选择语句,1个用于获取最新的失败状态,1个用于获取最新的错过状态。在第3个我需要有一个声明,如果最新状态是错过或失败但似乎已合并数据?即时通讯使用LIKE,因为错过和失败可能会略有不同

mysql> select max(scheduled_start),node_name,schedule_name,status from `events_server` WHERE status LIKE '%Failed%'and node_name='name';
+----------------------+----------------+---------------+-----------+
| max(scheduled_start) | node_name      | schedule_name | status    |
+----------------------+----------------+---------------+-----------+
| 2013-01-30 15:00:00  | name           | name_1500     | Failed  1 |
+----------------------+----------------+---------------+-----------+
1 row in set (0.01 sec)

mysql> select max(scheduled_start),node_name,schedule_name,status from `events_server` WHERE status LIKE '%Missed%'and node_name='name';
+----------------------+----------------+---------------+--------+
| max(scheduled_start) | node_name      | schedule_name | status |
+----------------------+----------------+---------------+--------+
| 2013-01-23 08:00:00  | name           | NAME_0800     | Missed |
+----------------------+----------------+---------------+--------+
1 row in set (0.01 sec)

mysql> select max(scheduled_start),node_name,schedule_name,status from `events_server` WHERE (status LIKE '%Failed%' OR status LIKE '%Missed%') and node_na
me='name';
+----------------------+----------------+---------------+--------+
| max(scheduled_start) | node_name      | schedule_name | status |
+----------------------+----------------+---------------+--------+
| 2013-01-30 15:00:00  | name           | NAME_0800     | Missed |
+----------------------+----------------+---------------+--------+
1 row in set (0.01 sec)

1 个答案:

答案 0 :(得分:1)

您是否尝试过类似于 pivot 数据的内容,并为每个状态返回单独的列。这将为max(scheduled_start)Failed状态提供Missed。但您还需要添加GROUP BY才能获得结果:

select 
    max(case when status LIKE '%Failed%' then scheduled_start end) Failed,
    max(case when status LIKE '%Missed%' then scheduled_start end) Missed,
    node_name,
    schedule_name
from `events_server`
where node_name='name'
 AND (status LIKE '%Missed%' OR status LIKE '%Failed%')
group by node_name, schedule_name