0

MySQL软件表:

.------------------------------------------------------------.
| id | hostname   | software | version | install_date        |
|------------------------------------------------------------|
| 1  | computer-a | vim      | 1.00    | 2012-01-04 00:00:00 | 
|------------------------------------------------------------|
| 1  | computer-a | vim      | 2.00    | 2012-01-05 00:00:00 | 
|------------------------------------------------------------|
| 1  | computer-b | emacs    | 2.00    | 2012-01-04 00:00:00 | 
|------------------------------------------------------------|
| 1  | computer-b | emacs    | 1.00    | 2012-01-05 00:00:00 | 
|------------------------------------------------------------|
| 1  | computer-c | emacs    | 2.00    | 2012-01-05 00:00:00 | 
|------------------------------------------------------------|
| 1  | computer-c | vim      | 3.00    | 2012-01-05 00:00:00 | 
'------------------------------------------------------------'

MySQL查询:

SELECT 
  hostname,
  MAX(IF(software = 'vim', version, NULL)) AS VIM,
  MAX(IF(software = 'emacs', version, NULL)) AS EMACS
FROM
  software
GROUP BY
  hostname;

结果:

+-------------+---------+----------+
| hostname    | VIM     | EMACS    |
+-------------+---------+----------+
| computer-a  | 2.0     | NULL     |
+-------------+---------+----------+
| computer-b  | NULL    | 2.0      |
+-------------+---------+----------+
| computer-c  | 3.0     | 2.0      |
+-------------+---------+----------+

http://www.sqlfiddle.com/#!8/6247d/3

问题是我想显示install_date每个software. Computer-b 应该为 EMACS 显示 1.0。如何更改查询以完成此操作?

我可以将查询更改为:

SELECT 
  hostname,
  MAX(IF(software = 'vim', install_date, NULL)) AS VIM,
  MAX(IF(software = 'emacs', install_date, NULL)) AS EMACS
FROM
  software
GROUP BY
  hostname;

这会拉出正确的 install_date 但我怎样才能显示相应的version

http://www.sqlfiddle.com/#!8/6247d/4

4

1 回答 1

1

您可以使用子查询来获取max(install_date)每个hostname,然后将其连接回您的表:

select s1.hostname,
  MAX(IF(software = 'vim', version, NULL)) AS VIM,
  MAX(IF(software = 'emacs', version, NULL)) AS EMACS
from software s1
inner join
(
  select max(install_date) i_date,
    hostname
  from software
  group by hostname
) s2
  on s1.install_date = s2.i_date
  and s1.hostname = s2.hostname
group by s1.hostname

请参阅SQL Fiddle with Demo。结果是:

|   HOSTNAME |    VIM |  EMACS |
--------------------------------
| computer-a |   2.00 | (null) |
| computer-b | (null) |   1.00 |
| computer-c |   3.00 |   2.00 |

如果可能有不同的,您可能需要在子查询中group by使用hostname和:softwaresoftwareinstall_date

select s1.hostname,
  MAX(IF(s1.software = 'vim', version, NULL)) AS VIM,
  MAX(IF(s1.software = 'emacs', version, NULL)) AS EMACS
from software s1
inner join
(
  select max(install_date) i_date,
    hostname, software
  from software
  group by hostname, software
) s2
  on s1.install_date = s2.i_date
  and s1.hostname = s2.hostname
group by s1.hostname

请参阅带有演示的 SQL Fiddle

于 2013-03-29T00:46:26.670 回答