简体   繁体   English

从两个表中选择一行的最大值

[英]select max value of a row from two tables

Please i am trying to query data with a maximum value from two tables, 请我尝试从两个表中查询具有最大值的数据,

table1
|user_id | name |
| 001    | Paul |
| 002    | Sean |


table2
|id  | class | Year | user_id |
|201 |  1A   | 2010 |  001    |
|202 |  2A   | 2011 |  001    |
|203 |  1B   | 2010 |  002    |

The user_id in table2 references the user_id from table1 user_idtable2引用user_idtable1

This is how i want my output to be 这就是我希望我的输出是

OUTPUT
 | user_id | name | class| year |
 | 001     | Paul | 2A   | 2011 |
 | 002     | Sean | 1B   | 2010 |

TRIED SO FAR 试过这么远

SELECT 
       a.user_id,
       a.name,
       b.class,
       max(Year) as year
FROM
       table1 a
INNER JOIN
           table2 b
    ON
           a.user_id=b.user_id

GROUP BY user_id

This query above gives me a maximum year with a different class value in a row, thus the previous class value. 上面的查询为我提供了一个最大年份,该年份中连续有一个不同的类别值,因此是前一个类别值。 This is how it looks like 看起来像这样

 | user_id | name | class| year |
 | 001     | Paul | 1A   | 2011 |
 | 002     | Sean | 1B   | 2010 |

Please where am i going wrong in my query? 请问我在哪里查询错了? Any help is appreciated. 任何帮助表示赞赏。 Thanks 谢谢

Maybe you could order the full result set first by year, and then group by user id: 也许您可以先按年份订购完整结果集,然后再按用户ID分组:

SELECT * FROM (

SELECT 
       a.user_id,
       a.name,
       b.class,
       year
FROM
       table1 a
INNER JOIN
           table2 b
    ON
           a.user_id=b.user_id
ORDER BY year desc

) h
GROUP BY user_id

SqlFiddle demo here SqlFiddle演示在这里

Because you are using group by already, you can use the substring_index() / group_concat() hack: 因为您已经在使用group by ,所以可以使用substring_index() / group_concat() hack:

SELECT a.user_id, a.name,
       substring_index(group_concat(b.class order by year desc), ',', 1) as maxclass
       max(Year) as year
FROM table1 a INNER JOIN
     table2 b
     ON a.user_id=b.user_id
GROUP BY a.user_id, a.name;

You can also do this without a group by , using not exists : 您也可以不使用group by来执行此操作,使用not exists

SELECT a.user_id, a.name, b.class, b.year
FROM table1 a INNER JOIN
     table2 b
     ON a.user_id=b.user_id
WHERE NOT EXISTS (select 1 from table2 b2 where b2.user_id = b.user_id and b2.year > b.year)

The where clause rephrases the query. where子句改写查询。 It says: "Get me all rows from table2 where the same user does not have a bigger year ." 它说:“让我从table2所有行获得,其中同一用户没有更大的year 。” This is equivalent to getting the row with the maximum year. 这等效于获得最大年份的行。 And, this is standard SQL, which often works quite well in any database. 而且,这是标准的SQL,在任何数据库中通常都可以很好地工作。

Try using a subquery 尝试使用子查询

SELECT 
       a.user_id,
       a.name,
       (Select class  FROM table2 where year = max(b.year)) as class,
       max(b.Year) as year
FROM
       table1 a,table2 b
WHERE
      a.user_id=b.user_id

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM