根据不同表中的最大值从表中选择行

时间:2014-11-29 09:21:46

标签: mysql sql select group-by max

我正在寻找MySQL查询来提取以下示例中的值:

TABLE1:
 ID     name   
 25     ab       
 24     abc      
 23     abcd       
 22     abcde      
 21     abcdef 


 TABLE2:
 ID     ID_TABLE1   total       
 1      25          0
 2      25          1
 3      25          2
 4      25          3
 5      23          1
 6      22          0
 7      22          1
 8      21          0
 9      21          2
 10     24          10
 11     24          7

我想返回TABLE1列的最大值(total)中的所有TABLE2行< 3。  所以结果应该是:

 ID     name   
 23     abcd       
 22     abcde      
 21     abcdef 

我试过了:

SELECT t1.*
FROM TABLE1 t1
INNER JOIN (
        SELECT MAX( total ) AS max_total, ID_TABLE1
        FROM TABLE2
        GROUP BY total, ID_TABLE1
) t2
ON t1.ID = t2.ID_TABLE1
WHERE t2.max_total < 3

但这不是我想要的结果。

6 个答案:

答案 0 :(得分:3)

试试这个:

SELECT t1.ID, t1.name
FROM TABLE1 t1
INNER JOIN (SELECT ID_TABLE1, MAX(total) AS max_total 
            FROM TABLE2 
            GROUP BY ID_TABLE1 
          ) t2 ON t1.ID = t2.ID_TABLE1 
WHERE t2.max_total < 3;

答案 1 :(得分:2)

您的内部查询按id_table 和总计对结果进行分组。由于每total total的最大值是值本身,因此它使内部查询无意义。只需从total子句中删除group by,您就可以了:

SELECT t1.*
FROM TABLE1 t1
INNER JOIN (
        SELECT   MAX( total ) AS max_total, ID_TABLE1
        FROM     TABLE2
        GROUP BY ID_TABLE1
) t2
ON t1.ID = t2.ID_TABLE1
WHERE t2.max_total < 3

答案 2 :(得分:1)

 SELECT t1.*
FROM TABLE1 t1
INNER JOIN (
    SELECT   MAX( total ) AS max_total, ID_TABLE1
    FROM     TABLE2
    GROUP BY ID_TABLE1
    having t2.max_total < 3
  ) t2
 ON t1.ID = t2.ID_TABLE1

答案 3 :(得分:1)

以下是使用left join而不使用任何子查询和group by子句的方法。

select t1.* from table1 t1
join table2 t2
on t1.id = t2.id_table1
left join table2 t3 on
t2.id_table1 = t3.id_table1
and t2.total < t3.total
where t3.id is null
and t2.total < 3

另一种方式是

select t1.* from table1 t1
join table2 t2 on t1.id = t2.id_table1
where not exists(
  select 1 from table2 t3
  where t2.id_table1 = t3.id_table1
  and t2.total < t3.total
)
and t2.total < 3;

答案 4 :(得分:0)

SELECT t1。*

FROM TABLE1 t1

INNER JOIN(

    SELECT MAX( total ) AS max_total, ID_TABLE1
    FROM TABLE2
     where total > 3  GROUP BY total, ID_TABLE1 

)t2 ON t1.ID!= t2.ID_TABLE1

答案 5 :(得分:0)

没有使用GROUPMAX,有一种更简单的方式:

SELECT * FROM table1
WHERE id NOT IN (
    SELECT id_table1 FROM table2 WHERE total >= 3
);

子查询选择table2中总数> = 3的所有行。然后我们从table1中选择那些不在子查询结果中的行。