How to select the id with max value that in another table

user6456568 :

Here are 2 tables.

Table 1
id  value
1   3
2   2
3   3
4   1
5   4
6   3
Table 2
id
1
3
4

How do I get the ids that are in Table 2 which have the max value in Table 1?

Output:

id
1
3

I already tried the following to get the max value, but I cannot figure out how to use it in a single query to get the matching rows. Because I think I need to select from the same table I just inner joined.

select max(table1.value) 
from table2 
inner join table1 on table1.id = table2.id;
Nick :

You have a couple of options available without using window functions:

  1. You can use a WHERE clause to select only id values that have a value equal to the MAX(value) from your query and an id that is in Table2:
    SELECT t1.id
    FROM Table1 t1
    WHERE value = (
      SELECT MAX(t1.value)
      FROM Table2 t2
      JOIN Table1 t1 ON t1.id = t2.id
    )
    AND id IN (SELECT id FROM Table2)
  1. You can JOIN your query to Table1 and Table2 again, matching the value in Table1 and the id in Table2:
    SELECT t1.id
    FROM (
      SELECT MAX(t1.value) AS max_value
      FROM Table2 t2
      JOIN Table1 t1 ON t1.id = t2.id
    ) t
    JOIN Table1 t1 ON t1.value = t.max_value
    JOIN Table2 t2 ON t2.id = t1.id

In both cases the output is

id
1
3

Demo on SQLFiddle

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=13862&siteId=1