0

我有两个表,A 和 B,A 包含条目列表,B 包含每个条目的多个状态行(0-n,按日期分组,状态 0 表示正常,1 表示失败)。

现在我想从 A 中选择所有行,包括它们各自的最新状态及其日期以及最近的失败及其日期(失败定义为至少有一个条目为 1)。

我尝试了两个左连接,但不相信这是最佳解决方案,并且在确定正确的失败次数方面仍然存在问题(SUM(b2.status))

SELECT a.id, b1.date, SUM(b1.status), b2.date, SUM(b2.status) FROM tablea a
LEFT JOIN tableb b1 ON b1.aid=a.id
LEFT JOIN tableb b2 ON b2.aid=a.id

WHERE (b1.date=(SELECT MAX(`date`) FROM tableb WHERE aid=a.id) OR b1.date IS NULL)
AND (b2.date=(SELECT MAX(`date`) FROM tableb WHERE aid=a.id GROUP BY `date` HAVING SUM(`status`)>0) OR b2.date IS NULL)

GROUP BY a.id
4

4 回答 4

0

哎呀,我认为我在这一点上所做的每一个假设都是错误的。我想这会给你你想要的。它将为您提供最近发生故障的日期的故障总数。

我不确定在非常大的数据库上性能如何,但在较小的数据库上效果很好。

SELECT a.id, MAX(b1.date) status_date, SUM(b1.status) latest_status, 
       b2.date latest_failure,
       b2.total_failures

FROM tablea a

     LEFT JOIN tableb b1
     ON b1.aid = a.id
     AND b1.date = (SELECT MAX(date) FROM tableb WHERE aid = a.id)

     LEFT JOIN 
     (SELECT aid, date, count(*) total_failures FROM tableb WHERE status > 0 GROUP BY aid, date) b2
     ON b2.aid = a.id
     AND b2.date = (SELECT MAX(date) FROM tableb WHERE aid = a.id AND status > 0)

GROUP BY a.id;
于 2012-08-23T16:54:58.287 回答
0

像这样的东西应该工作。

SELECT a.id, b1.date status_date, b1.status, b2.date latest_failure, 
       (SELECT COUNT(*) FROM tableb WHERE aid = a.id AND status > 0) total_failures

FROM tablea a

     LEFT JOIN tableb b1
     ON b1.aid = a.id
     AND b1.date = (SELECT MAX(date) FROM tableb WHERE aid = a.id)

     LEFT JOIN tableb b2
     ON b2.aid = a.id
     AND b2.date = (SELECT MAX(date) FROM tableb WHERE aid = a.id AND status > 0)

这是假设 tableb.date 字段是日期时间并且是唯一的。否则,您可能希望使用 id 字段。

于 2012-08-23T14:27:03.107 回答
0

你也可以这样做。不确定哪个更有效。你可以尝试两种方式。

SELECT a.id, b1.date status_date, b1.status, 
       (SELECT MAX(date) FROM tableb WHERE aid = a.id AND status > 0) latest_failure, 
       (SELECT COUNT(*)  FROM tableb WHERE aid = a.id AND status > 0) total_failures

FROM tablea a

     LEFT JOIN tableb b1
     ON b1.aid = a.id
     AND b1.date = (SELECT MAX(date) FROM tableb WHERE aid = a.id)
于 2012-08-23T14:29:49.300 回答
0

这应该有效。

SELECT a.id, MAX(b1.date) status_date, SUM(b1.status) latest_status, 
       (SELECT MAX(date) FROM tableb WHERE aid = a.id AND status > 0) latest_failure,
       (SELECT COUNT(*) FROM tableb  WHERE aid = a.id AND status > 0) total_failures

FROM tablea a

     LEFT JOIN tableb b1
     ON b1.aid = a.id
     AND b1.date = (SELECT MAX(date) FROM tableb WHERE aid = a.id)

GROUP BY a.id;

如果您一天内可能有多次失败,并且希望将状态显示为“1”,请更改此:

SUM(b1.status) 最新状态

至:

MAX(b1.status) 最新状态。

于 2012-08-23T16:24:17.350 回答