左连接,排序,MySQL优化
作者:互联网
我有这样的查询:
SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN 0_area AS a ON a.user_id = (SELECT user_id
FROM `0_area`
WHERE user_id = m.id
ORDER BY sec_id ASC LIMIT 1)
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'
我们的想法是从0_area表中获取第一行,从而获得内部连接.但是,它没有按预期工作.
在0_area和0_member之间,0_member.id = 0_area.user_id.但是,有多行0_area.user_id,我希望行具有最低值sec_id.
有什么帮助吗?
解决方法:
SELECT m...., a...., r....
FROM 0_member AS m
LEFT JOIN (SELECT user_id, min(sec_id) minsec
FROM `0_area`
GROUP BY user_id) g1 on g1.user_id=m.id
LEFT JOIN 0_area AS a ON a.user_id = g1.user_id and a.sec_id=minsec
LEFT JOIN 0_rank as r ON a.rank_id = r.id
WHERE m.login_userid = '$username'
标签:outer-join,sql,mysql,left-join 来源: https://codeday.me/bug/20190827/1737159.html