在对表进行分组后将内部连接表自身分解

时间:2014-12-17 10:14:48

标签: php mysql

我已经生成了以下查询来搜索表并仅返回多次出现,如此(最多出现次数为2次):

SELECT * FROM spin
            WHERE `serial` in (
            SELECT `serial` from spin group by `serial`
            HAVING count(*) > 1
            ) ORDER BY test_started DESC

在此表中,每条记录都有一个test_started列,然后我将循环遍历结果集,如下所示:

<?php foreach ($tests as $test) { ?>
<tr>
<td><?php if (isset($test->model)) echo $test->model; ?></td>
<td><?php if (isset($test->serial)) echo $test->serial; ?></td>
<td><?php if (isset($test->error_count)) echo $test->error_count; ?></td>
<td><?php if (isset($test->max_temp)) $test_temp = substr($test->max_temp, -2); echo $test_temp; ?></td>
<td><?php if (isset($test->test_started)) echo $test->test_started; ?></td>
<td><?php if (isset($test->test_ended)) echo $test->test_ended; ?></td>
</tr>
<?php } ?>

我想要做的是将匹配的序列分组到一列,我猜测需要某种DISTINCT查询,然后显示第一个和第二个test_started日期

1 个答案:

答案 0 :(得分:0)

根据我的理解,您希望最多2个serials计数相同且您想要第一个和开始日期,所以现在尝试一下:

SELECT A.model, A.`serial`, A.error_count, A.max_temp, A.test_started, B.test_ended
 FROM ( 
  SELECT model, `serial`, error_count, max_temp, test_started 
  FROM spin 
  WHERE `serial` in (
    SELECT `serial` from spin group by `serial`
    HAVING count(*) = 2
    ) 
    GROUP BY `serial`, test_started ASC
 ) A
 INNER JOIN
 (
  SELECT model, `serial`, error_count, max_temp, test_started as test_ended
  FROM spin 
  WHERE `serial` in (
    SELECT `serial` from spin group by `serial`
    HAVING count(*) = 2
    ) 
  GROUP BY `serial`, test_started DESC
  ) B
  ON A.`serial` = B.`serial`
  GROUP BY A.`serial

参见 Demo