你可以试试这样的:
select main.*
FROM
-- get all information from t1 and amount from t2
(
select t1.*, t2.amount from t1 inner join t2 on t1.id = m_id
) main
INNER JOIN
-- get max amount by department
(
select department, max(amount) max_amount from t1 inner join t2 on t1.id = m_id
group by department
) summary
-- match with main by department and the max amount
on main.department = summary.department
and main.amount = summary.max_amount;
结果
+------+----------------+------------+--------+
| id | name | department | amount |
+------+----------------+------------+--------+
| 1 | John Abraham | HR | 5000 |
| 2 | Michael Clarke | HR | 5000 |
| 3 | Roy Thomas | Manager | 2500 |
+------+----------------+------------+--------+
示例在这里:https://dbfiddle.uk/?rdbms=mysql_5.7&fiddle=a4cdd94b415df204b0fd967263ba9dc8
解释
由于您想按部门获取最大金额,我们为此创建了一个子查询。我们给它一个别名summary。这给了我们这个:
select department, max(amount)
from t1 inner join t2 on t1.id = m_id group by department;
+------------+-------------+
| department | max(amount) |
+------------+-------------+
| HR | 5000 |
| Manager | 2500 |
+------------+-------------+
我们通过合并 t1 和 t2 表来合并您想要报告的数据,并为其命名为 main。这给了我们这个:
select t1.*, t2.amount from t1 inner join t2 on t1.id = m_id;
+------+----------------+------------+--------+
| id | name | department | amount |
+------+----------------+------------+--------+
| 1 | John Abraham | HR | 5000 | <-- want this
| 2 | Michael Clarke | HR | 5000 | <-- want this
| 3 | Roy Thomas | Manager | 2500 | <-- want this
| 4 | Jerry Pinto | Manager | 1000 |
| 4 | Tom Jose | HR | 1000 |
+------+----------------+------------+--------+
然后,我们确保根据部门和两个子查询中的金额连接两个子查询。