从表中获取字段x的值最大的行

时间:2016-04-01 18:42:13

标签: mysql sql database

我在mysql数据库中有两个表 myTable myTable2

CREATE TABLE myTable (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    number INT,
    version INT, 
    date DATE 
) ENGINE MyISAM;

INSERT INTO myTable
    (`id`, `number`, `version`, `date`)
VALUES
    (1, '123', '1', '2016-01-12'),
    (2, '123', '2', '2016-01-13'),
    (3, '124', '1', '2016-01-14'),
    (4, '124', '2', '2016-01-15'),
    (5, '124', '3', '2016-01-16'),
    (6, '125', '1', '2016-01-17')
;

CREATE TABLE myTable2 (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    myTable_id INT
) ENGINE MyISAM;

INSERT INTO myTable2
    (`id`, `myTable_id`)
VALUES
    (1, 1),
    (2, 1),
    (3, 2),
    (4, 2),
    (5, 3),
    (6, 3),
    (7, 4),
    (8, 4),
    (9, 4),
    (10, 5),
    (11, 6)
;

字段 myTable2.myTable_id myTable.Id 的外键。

我想获取 myTable 中的所有行,其中 myTable2.myTable_id = myTable.Id 以及字段版本的值 myTable myTable 中字段数字的每个对应值的最大值。

我试过这样的事情:

SELECT 
    * 
FROM 
    myTable, 
    myTable2 
WHERE 
    myTable.version = (SELECT MAX(myTable.version) FROM myTable)

但是上面的查询没有返回正确的数据。正确的查询应输出:

Id     number    version    date
2      123       2          2016-01-13
5      124       3          2016-01-16
6      125       1          2016-01-17

请帮忙!

4 个答案:

答案 0 :(得分:3)

执行此操作的一种方法是在派生表中获取myTable中每个数字的最大版本并加入:

SELECT DISTINCT 
    m.* 
FROM 
    myTable m
JOIN
    myTable2 m2 ON m.id = m2.myTable_id
JOIN
    (
    SELECT number, MAX(version) AS max_version 
    FROM myTable
    GROUP BY number
    ) AS derived_table
 ON m.number  = derived_table.number 
AND m.version = derived_table.max_version

使用您的示例数据,会产生如下结果:

id  number  version date
6   125     1       2016-01-17
5   124     3       2016-01-16
2   123     2       2016-01-13

答案 1 :(得分:1)

您的查询在逻辑上是错误的。这是正确的

SELECT 
 * 
FROM 
 myTable, 
 myTable2 
WHERE 
 (myTable.version,myTable.number) in 
  (SELECT MAX(myTable.version),number FROM myTable group by number)
 and myTable.id=myTable2.id

这是sqlfiddle http://sqlfiddle.com/#!9/74a67/4/0

答案 2 :(得分:0)

这是针对上一个编辑过的问题发布的查询

SELECT * FROM myTable 
inner join myTable2 on myTable.id = myTable2.mytable_id
WHERE (version, number) in 
  (SELECT MAX(version), number FROM myTable group by number)

答案 3 :(得分:0)

使用子查询尝试此解决方案,简单如下:

# Selecting desired result..
SELECT t1.id, t1.number, t1.version, t1.date 
FROM myTable As t1 JOIN
    # subquery to select max version and its corresponding
    # number form myTable
    (SELECT number, max(version) As max_ver FROM myTable
        GROUP BY number
    ) As t2 ON  t1.number = t2.number and t1.version = t2.max_ver

# Now checking for foreign key..
WHERE t1.id IN (SELECT mytable_id FROM myTable2);

有用吗..