MySQL - 将行合并为一个

时间:2013-04-28 15:44:41

标签: php mysql sql database

我搜索了各种问题,但我找不到答案。 我有一个MySQL表'团队':

+--+----+------+
|id|name|active|
+--+----+------+
|1 |bla |1     |
|2 |blu |0     |
|3 |croc|1     |
|4 |bold|1     |
|5 |foo |1     |
|6 |bar |0     |
+--+----+------+

和表'数据':

+----+-------+----+
|team|project|time|
+----+-------+----+
|2   |some   |1   |
|2   |some2  |5   |
|3   |one    |16  |
|3   |one2   |100 |
|5   |more   |2   |
|5   |more2  |60  |
+----+-------+----+

在PHP中,我正在查询这样的数据:

SELECT t.name, t.active, d.time
FROM teams t
RIGHT JOIN data d ON (t.id = d.team)
ORDER BY t.id

一切正常,我的结果如下:

+----+------+----+
|name|active|time|
+----+------+----+
|blu |0     |1   |
|blu |0     |5   |
|croc|1     |16  |
|croc|1     |100 |
|foo |1     |2   |
|foo |1     |60  |
+----+------+----+

...但我希望我的结果如下:

+----+------+---+---+
|name|active|t1 |t2 |
+----+------+---+---+
|blu |0     |1  |5  |
|croc|1     |16 |100|
|foo |1     |2  |60 |
+----+------+---+---+

所以......我怎么能达到这个目的?我希望我没有忽视一个已经问过的问题...... :(

非常感谢!

编辑:首先,谢谢大家,但我忘记了一些事情......也有可能是one2不存在......

2 个答案:

答案 0 :(得分:2)

试试这个

 SELECT t.name, t.active, 
 min(time) t1, max(time)t2
FROM teams t
RIGHT JOIN data d ON (t.id = d.team)
group by name
ORDER BY t.id

DEMO HERE

编辑:

试试这个

   SELECT t.name, t.active, 
   min(time) t1, if  (  max(time) is not null and max(time) <> min(time) , max(time), null )t2
  FROM teams t
  RIGHT JOIN data d ON (t.id = d.team)
  group by name
  ORDER BY t.id

DEMO HERE

答案 1 :(得分:0)

如果每个队伍最多有两行冷,我会使用类似的东西:

SELECT
  teams.name,
  teams.active,
  min(d1.time) t1,
  max(d2.time) t2
FROM
  teams INNER JOIN data d1
  ON teams.id=d1.team
  LEFT JOIN data d2
  ON teams.id=d2.team AND d1.time<d2.time
GROUP BY
  teams.name,
  teams.active