简体   繁体   English

MySQL查询:从其他表中选择所有ID和相应的最大值

[英]MySQL query: select all ID's and corresponding max value from other table

What I want: selecting all ID's from table1 and a max value from table2.我想要的是:从 table1 中选择所有 ID,从 table2 中选择最大值。 If table2 doesn't contain an id, 0 is its max value.如果 table2 不包含 id,则 0 是其最大值。 Query I got so far:到目前为止我得到的查询:

SELECT t1.Id, max(t2.value) FROM table1 t1 JOIN table2 t2 USING(Id) GROUP BY t2.Id;

But the problem with this query is that it only returns an id if it is in both tables.但是这个查询的问题是它只返回一个 id 如果它在两个表中。 How can I select all id's from table1 and a 0 or a max value from table2?如何从 table1 中选择所有 id 并从 table2 中选择 0 或最大值?

This is the case to use a LEFT join:这是使用 LEFT 连接的情况:

SELECT t1.Id, coalesce(max(t2.value), 0) 
FROM table1 t1 LEFT JOIN table2 t2 
USING(Id) 
GROUP BY t1.Id;

I also changed the GROUP BY clause to use t1.id instead of t2.id .我还将 GROUP BY 子句更改为使用t1.id而不是t2.id

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

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