我有两张桌子 - 表1:
id name number
------------------
1 x1 123
2 x2 234
......和表2:
tbl1id title rank
--------------------
1 t1 3
1 t2 2
2 t1 3
1 t3 1
有没有办法可以加入他们返回结果,根据给定用户的最低排名显示最大标题:
id name number max_title rank
----------------------------------
1 x1 123 't3' 1
2 x2 234 't1' 3
问题已更新!
答案 0 :(得分:2)
使用:
SELECT t.id,
t.name,
t.number,
COALESCE(x.max_title, 'no title associated') AS max_title
FROM TABLE1 t
LEFT JOIN (SELECT t2.tbl1id,
MAX(t2.title) 'max_title'
FROM TABLE2 t2
WHERE t2.rank = (SELECT MIN(rank)
FROM TABLE2
WHERE tbl1id = t2.tbl1id)
GROUP BY t2.tbl1id) x ON x.tbl1id = t.id
答案 1 :(得分:0)
SELECT t1.id, t1.name, t1.number, MAX(t2.title)
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.id = t2.tbl1id
GROUP BY t1.id, t1.name, t1.number
修改强>
- 更新为使用LEFT JOIN,因为在给定id的情况下,table2中可能没有记录
- 答案现在无关紧要,因为自原始问题以来问题已经改变。留下历史。