本周工作中碰到了兩個1對多表的關聯查詢只要查詢出相關聯的第一條數據的情況,之前沒有使用過分析函數,查了下資料了解了一些。
demo1
--員工表(employees)結構
--ID 姓名 工資 部門ID
-- id name salary dept_id
--查詢每個部門工資最高的人
select id , name,salary,dept_id from (select id , name,salary,dept_id rank()
over(partition by dept_id order by salary desc) rank from employees) t
where t.rank = 1
demo2
--查詢每個人與部門最高工資的差額
select id , name,salary,(max(salary) over(partition by dept_id)
- salary) diff_max_salary,dept_id
from employees
解決方案
select firm_id,firm_name,contact_id,contact_name from
(select a.id firm_id,a.name firm_name,b.id contact_id,b.name contact_name,
rank() over(partition by a.id order by b.id) rank
from firms a left join contacts b on a.id = b.firm_id
where a.phone like :phone or b.phone like :phone) t where t.rank=1